package com.gexin.service.agent;

import com.alibaba.fastjson.JSONObject;
import com.alipay.AlipaySDK;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.gexin.common.AppGlobal;
import com.gexin.common.kusy.KusyApi;
import com.gexin.common.kusy.KusyUtil;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.*;
import com.gexin.controller.commom.WeixinTransfer.WeixinTransferUtil;
import com.gexin.controller.commom.WeixinTransfer.model.WeixinTransferResult;
import com.gexin.controller.weixin.subscribe.SubscribeMessageKit;
import com.gexin.controller.weixin.subscribe.WxaSubscribeMessage;
import com.gexin.controller.weixin.subscribe.WxaSubscribeMessageApi;
import com.gexin.model.AgentPhone;
import com.gexin.model.WxOrderRefund;
import com.gexin.model.activity.Activity;
import com.gexin.model.activity.UserActivity;
import com.gexin.model.agent.*;
import com.gexin.model.order.*;
import com.gexin.model.product.Products;
import com.gexin.model.promo.PromoCode;
import com.gexin.model.promo.PromoInfo;
import com.gexin.model.promo.Promotional;
import com.gexin.model.shop.ShopInfo;
import com.gexin.model.system.AddrAreas;
import com.gexin.model.system.AddrCities;
import com.gexin.model.system.AdminLog;
import com.gexin.model.system.AdminUser;
import com.gexin.model.user.UserCoupon;
import com.gexin.model.user.UserRebate;
import com.gexin.model.weixin.UserAddress;
import com.gexin.model.weixin.WeixinAppConfig;
import com.gexin.model.weixin.WeixinUser;
import com.gexin.weixin.uitls.WxConfig;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.cache.DefaultAccessTokenCache;
import com.jfinal.wxaapp.WxaConfigKit;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.util.*;

@Before(Tx.class)
public class AgentService {
    public static AgentService dao = new AgentService();

    private static Log log = Log.getLog(AgentService.class);


    public Page<Agent> findAgentList(int page, int pageSize, String name, String phone, String type) {
        Page<Agent> agentList = Agent.dao.findAgentList(page, pageSize, name, phone, type);
        for (Agent agent : agentList.getList()) {
            List<AgentCity> cityList = AgentCity.dao.findByAgentId(agent.getId(), AgentCity.STATUS_SUCCESS);
            agent.put("cityList", cityList);

//			AgentProductSku agentProductSku = AgentProductSku.dao.findByAgentId(agent.getId().toString(),);
//			if (null!=agentProductSku) {
//				Integer stockNum = agentProductSku.getStockNum();
//				Integer saleNum = agentProductSku.getSaleNum();
//				agent.put("stockNum", stockNum==null?0:stockNum);
//				agent.put("saleNum", saleNum==null?0:saleNum);
//			}
        }

        System.out.println(agentList);
        return agentList;
    }

    /**
     * 给区域代理商添加金额
     *
     * @param id
     * @param priceStr
     */
    public ApiResponse areaAddSubsidy(String id, String priceStr, String orderId) {
        Agent agent = Agent.dao.findById(id);
        if (StringUtils.isBlank(priceStr)) {
            return new ApiResponse(false, "价格不能为空!");
        }
        if (null == agent) {
            return new ApiResponse(false, "该代理商不是区域代理!");
        }
        Integer agentLe = agent.getAgentLevel();
//		if(null==agentLe||5!=agentLe){
//			return new ApiResponse(false , "该id不是区域代理商!");
//		}
        BigDecimal subsidies = new BigDecimal(priceStr);
        BigDecimal zero = new BigDecimal("0");
        if (null == subsidies && zero.compareTo(subsidies) > 0) {
            return new ApiResponse(false, "输入的金额不能为0或者小于0!");
        }
        //		AgentLevel agentLevel = AgentLevel.dao.findById(id);
//		BigDecimal discount = agentLevel.getDiscount();
//		BigDecimal discountAmount = price.multiply(discount);
        BigDecimal agentPrice = agent.getPrice();
        if (null == agentPrice) {
            agentPrice = new BigDecimal("0.00");
        }
        BigDecimal agentPriceAddSubsidies = agentPrice.add(subsidies);
        BigDecimal accumulatedIncome = agent.getAccumulatedIncome();
        if (null == accumulatedIncome) {
            accumulatedIncome = new BigDecimal("0.00");
        }
        BigDecimal accumulatedIncomeAndSubsidies = accumulatedIncome.add(subsidies);
        agent.setPrice(agentPriceAddSubsidies);
        agent.setAccumulatedIncome(accumulatedIncomeAndSubsidies);
        agent.update();

        AgentAccountLog agentAccountLog = new AgentAccountLog();
        agentAccountLog.setId(IdGenerateUtils.getId());
        agentAccountLog.setPrice(subsidies);
        agentAccountLog.setState(AgentAccountLog.STATEIN);
        agentAccountLog.setCreateTime(new Date());
        agentAccountLog.setAgentId(Integer.parseInt(id));
        agentAccountLog.setBusiId(1);
        agentAccountLog.setAccountType(AgentAccountLog.ACCOUNTTYPEYE);
        agentAccountLog.setStatus(1);
        agentAccountLog.setOrderId(orderId);
        agentAccountLog.setEndTime(new Date());
//		agentAccountLog.setOrderPrice(price);
        agentAccountLog.setSonPrice(new BigDecimal("0.00"));
        agentAccountLog.setIsSonOrder(0);
        agentAccountLog.setType(6);
        Boolean flag = agentAccountLog.save();
        return new ApiResponse(flag, flag ? "区域补贴成功!" : "区域补贴失败!");
    }

    /**
     * 获取所有的区域的价格
     *
     * @param page     当前页
     * @param pageSize 每页条数
     * @param name
     * @return
     */
    public Page<AddrCities> findPageArea(Integer page, Integer pageSize, String name) {
        return AddrCities.dao.findPageArea(page, pageSize, name);
    }

    /**
     * 更新城市代理商价格
     *
     * @param city
     * @return
     */
    public ApiResponse updateCityAreaFee(AddrCities city) {
        if (city.getId() == null) {
            return new ApiResponse(false, "城市不存在!");
        }
        AddrCities findCity = AddrCities.dao.findById(city.getId());
        if (findCity.getAgentId() != null) {
            return new ApiResponse(false, "城市已经添加好了代理商!不能修改价格!");
        }
        boolean update = city.update();
        return new ApiResponse(update, update ? "价格修改成功!" : "价格修改失败!");
    }

    /**
     * 更新城市代理商价格
     *
     * @param addrAreas
     * @return
     */
    public ApiResponse updateAreaFee(AddrAreas addrAreas) {
        if (addrAreas.getId() == null) {
            return new ApiResponse(false, "城市不存在!");
        }
        AddrAreas findArea = AddrAreas.dao.findById(addrAreas.getId());
        if (findArea == null) {
            return new ApiResponse(false, "地区不存在");
        }
        if (findArea.getAgentId() != null) {
            return new ApiResponse(false, "城市已经添加好了代理商!不能修改价格!");
        }
        findArea.setAgentFee(addrAreas.getAgentFee());
        boolean update = findArea.update();
        return new ApiResponse(update, update ? "价格修改成功!" : "价格修改失败!");
    }


    /**
     * 代理商列表页
     *
     * @param page
     * @param pageSize
     * @param name
     * @param phone
     * @return
     */
//	public Page<Agent> findAgentList(int page , int pageSize , String name , String phone) {
//		Page<Agent> agentList = Agent.dao.findAgentList(page , pageSize , name , phone);
////
//		for (Agent agent : agentList.getList()) {
//			List<AgentCity> cityList = AgentCity.dao.findByAgentId(agent.getId() , AgentCity.STATUS_SUCCESS);
//			agent.put("cityList" , cityList);
//		}
//		return agentList;
//	}


    /**
     * 保存代理等级
     *
     * @param level
     * @return
     */
    public ApiResponse saveAgentLevel(AgentLevel level) {
        if (level == null) {
            return new ApiResponse(false, "等级不能为null!");
        }
        boolean boo;
        AgentLevel nameFirst = AgentLevel.dao.findByNameFirst(level.getName());
        if (level.getId() == null) {
            if (nameFirst != null) {
                return new ApiResponse(false, "等级名称已经存在!");
            }
            boo = level.save();
        } else {
            if (nameFirst != null && nameFirst.getId() != level.getId()) {
                return new ApiResponse(false, "等级名称已经存在!");
            }
            boo = level.update();
        }

        return new ApiResponse(boo, boo ? "操作成功!" : "操作失败");
    }

    /**
     * 获得代理等级分页信息
     *
     * @param page
     * @param pageSize
     * @return
     */
    public Page<AgentLevel> findLevelPageList(int page, int pageSize) {
        return AgentLevel.dao.findLevelPageList(page, pageSize);
    }


    /**
     * 保存区域代理商
     *
     * @param agent
     * @param cities
     * @param areaes
     * @param userId
     */

    public ApiResponse saveAreaAgent(Agent agent, String[] cities, String[] areaes, Integer userId) {
        StringBuffer stringBuffer = new StringBuffer();
        boolean returnboo;

        if (agent.getId() == null) {
            Agent agent1 = Agent.dao.findInfoByUserId(userId);
            if (agent1 != null) {
                agent1.setUserId(userId);
                agent1.setModifiedTime(new Date());
                agent = agent1;
                returnboo = agent1.update();
            } else {
                agent.setStatus(Agent.STATUS_WEICHULI);
                agent.setUserId(userId);
                agent.setModifiedTime(new Date());
                returnboo = agent.save();
            }

        } else {
            returnboo = agent.update();
        }
        if (returnboo) {
            for (int i = 0; i < cities.length; i++) {
                AddrCities city = AddrCities.dao.findByCityId(cities[i]);
                if (city != null) {
                    if (AddrCities.TYPE_OPEN_SUCCESS.equals(city.getIsArea())) {
                        AgentCity agentCity = AgentCity.dao.findByCityIdAndAgentId(agent.getId(), areaes[i]);
                        if (agentCity == null) {
                            agentCity = new AgentCity();
                            agentCity.setCityId(Integer.parseInt(cities[i]));
                            agentCity.setAreaId(Integer.parseInt(areaes[i]));
                            agentCity.setAgentId(agent.getId());
                            agentCity.setStatus(AgentCity.STATUS_NOTAUDIT);
                            agentCity.setTime(new Date());
                            boolean save = agentCity.save();
                            if (save) {
                                WeixinUser user = WeixinUser.dao.findById(userId);
                                new SendTemplateMessage().sendSubmitRegister(user.getOpenid());
                            }
                        }
                    } else {
                        AgentCity agentCity = AgentCity.dao.findByCityIdAndAgentId(agent.getId(), cities[i]);
                        if (agentCity == null) {
                            agentCity = new AgentCity();
                            agentCity.setCityId(Integer.parseInt(cities[i]));
                            agentCity.setAreaId(Integer.parseInt(areaes[i]));
                            agentCity.setAgentId(agent.getId());
                            agentCity.setStatus(AgentCity.STATUS_NOTAUDIT);
                            agentCity.setTime(new Date());
                            boolean save = agentCity.save();
                            if (save) {
                                WeixinUser user = WeixinUser.dao.findById(userId);
                                new SendTemplateMessage().sendSubmitRegister(user.getOpenid());
                            }
                        }
                    }

                }
            }
        }
        return new ApiResponse(returnboo, returnboo ? "代理商审核提交成功" : "代理商审核提交失败");
    }

    /**
     * 代理商审核
     *
     * @param agentCity
     * @param levelId
     * @param price
     * @param logintUser
     * @param deposit
     * @param sales
     * @param agencyFee
     */
    @Before(Tx.class)
    public ApiResponse audit(AgentCity agentCity, String levelId, String price, AdminUser logintUser, String deposit, String sales, String agencyFee) {

        boolean returnboo = false;
        if (agentCity.getStatus() == 1) {

            BigDecimal agentPrice = new BigDecimal(0);
            BigDecimal depositPrice = new BigDecimal(0);
            BigDecimal salesPrice = new BigDecimal(0);
            BigDecimal agencyFeePrice = new BigDecimal(0);
            try {
//			agentPrice = new BigDecimal(price);
                if (StringUtil.isNotBlank(deposit))
                    depositPrice = new BigDecimal(deposit);
                if (StringUtil.isNotBlank(sales))
                    salesPrice = new BigDecimal(sales);
                if (StringUtil.isNotBlank(agencyFee))
                    agencyFeePrice = new BigDecimal(agencyFee);
            } catch (NumberFormatException e) {
                return new ApiResponse(false, "金额输出错误");
            }

            //查询当前城市时候有其他代理商代理
            AddrCities addrCities = AddrCities.dao.findByCityId(agentCity.getCityId().toString());
            AddrAreas addrArea = null;
            if (addrCities == null) {
                return new ApiResponse(false, "城市信息不存在!");
            }
            if (addrCities.getIsArea() != null && addrCities.getIsArea() == 1) {
                if (agentCity.getAreaId() == null) {
                    return new ApiResponse(false, "代理区域不能为空!");
                }
                //查询县一级
                addrArea = AddrAreas.dao.findByAreaId(agentCity.getAreaId().toString());
                if (addrArea == null) {
                    return new ApiResponse(false, "代理城市不存在!");
                }
                if (addrArea.getAgentId() != null && addrArea.getAgentId() != agentCity.getAreaId()) {
                    return new ApiResponse(false, "该区域已被其他代理商代理!");
                }
                agentCity.setAreaType(AgentCity.TYPE_AREA);
            } else {
                if (addrCities.getAgentId() != null && addrCities.getAgentId() != agentCity.getCityId()) {
                    return new ApiResponse(false, "该城市已被其他代理商代理!");
                }
                agentCity.setAreaType(AgentCity.TYPE_CITY);
            }


            //同意代理的情况
            if (addrCities.getIsArea() != null && addrCities.getIsArea() == 1) {
                if (addrArea == null) {

                    return new ApiResponse(false, "代理城市不存在!");
                }
//				if((addrArea.getAgentFee()==null?new BigDecimal(0):addrCities.getAgentFee()).compareTo(depositPrice)>0){
//					return new ApiResponse(false,"金额小于区域代理金额");
//				}
            } else {
//				if((addrCities.getAgentFee()==null?new BigDecimal(0):addrCities.getAgentFee()).compareTo(depositPrice)>0){
//					return new ApiResponse(false,"金额小于城市代理金额");
//				}
            }
            agentCity.setSales(salesPrice);
            agentCity.setAgencyFee(agencyFeePrice);
            agentCity.setDeposit((agentCity.getDeposit() == null ? new BigDecimal(0) : agentCity.getDeposit()).add(depositPrice));
            agentCity.setAuditTime(new Date());
            agentCity.setAuditUser(logintUser.getId());
            agentCity.setIcePrice((agentCity.getIcePrice() == null ? new BigDecimal(0) : agentCity.getIcePrice()).add(agentPrice));
            agentCity.setAvailPrice(agentCity.getAvailPrice());
            returnboo = agentCity.update();
            if (returnboo) {
                if (AgentCity.TYPE_AREA.equals(agentCity.getAreaType())) {
                    addrArea.setAgentId(agentCity.getAgentId());
                    addrArea.update();
                } else {
                    addrCities.setAgentId(agentCity.getAgentId());
                    addrCities.update();
                }
                AgentAccountLog ac = new AgentAccountLog();
                ac.setId(IdGenerateUtils.getId());
                ac.setPrice(agentPrice);
                ac.setType(AgentAccountLog.TYPE_AUDIT);
                ac.setAccountType(AgentAccountLog.ACCOUNTTYPEHK);
                ac.setStatus(Agent.STATUS_SUCCESS);
                ac.setCreateTime(new Date());
                ac.setState(AgentAccountLog.STATEIN);
                boolean save = ac.save();
                Agent agent = Agent.dao.findById(agentCity.getAgentId());
                //生成代理商二维码
                qrCode(agent);
                agentQrCode(agent);
                agent.setStatus(Agent.STATUS_SUCCESS);
                agent.setIsPlatformAgent(Agent.ISPALTFROMTRUE);
                agent.setProductPrice((agent.getProductPrice() == null ? new BigDecimal(0) : agent.getProductPrice()).add(agentPrice));
                agent.update();
                WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());
                weixinUser.setIsAgent(1);
                weixinUser.update();
                MessageUtils.sendTemplateSMS(agent.getAgentPhone(), MessageUtils.ADUIT_SUCCESS_ID, new String[]{""});
            }

            return new ApiResponse(returnboo, returnboo ? "审核成功!" : "审核失败!");
        } else if (agentCity.getStatus() == 0) {

//		    不同意代理的情况
            //退款.删除代理商信息.充值用户信息
            Integer agentId = agentCity.getAgentId();
            Agent agent = Agent.dao.findById(agentId);
            returnboo = agentCity.delete();
            WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());
            if (returnboo) {
                ApiResponse apiResponse = auditNo(agent, weixinUser);
                MessageUtils.sendTemplateSMS(agent.getAgentPhone(), MessageUtils.ADUIT_FAIL_ID, new String[]{""});
                return apiResponse;
            }
        }
        return new ApiResponse(returnboo, returnboo ? "操作成功" : "操作失败");
    }

    private ApiResponse auditNo(Agent agent, WeixinUser weixinUser) {

        WeixinAppConfig weixinAppConfig = WeixinAppConfig.dao.findById(2);
        Integer cashDepositState = agent.getCashDepositState();
        boolean execute_state_cashDepositState = false;// 执行的状态
        boolean execute_state_controlMoneyAmount = false;// 执行的状态
        if (cashDepositState != null && cashDepositState == 1) {
            //退保证金
            BigDecimal cashDeposit = agent.getCashDeposit();
            AgentAccountLog agentAccountLog = AgentAccountLog.dao.findFirst("select * from t_agent_account_log where status=1 and type=1 and agent_id=?", agent.getId());
            if (agentAccountLog != null) {
                if (AppGlobal.dev_Mode) {
                    cashDeposit = new BigDecimal(0.01);
                }
                String refundNo = IdGenerateUtils.getId();
                String out_refund_id = null;// 外部退款的流水编号

                Map<String, String> result_map = null;
                String refund_recv_accout = "微信公众号";
                String ret = KusyApi.refund(KusyUtil.Api_key, KusyUtil.Sign_Key, agentAccountLog.getTransactionId(), cashDeposit.doubleValue(), refundNo);
                JSONObject ret_obj = JSONObject.parseObject(ret);
                WxOrderRefund wxOrderRefund = new WxOrderRefund();
                wxOrderRefund.setOrderId(agentAccountLog.getId());
                wxOrderRefund.setCreateTime(new Date());
                wxOrderRefund.setType(WxOrderRefund.cancelType_quane);
                wxOrderRefund.setRefundId(refundNo);
                wxOrderRefund.setOperator(weixinUser.getId());
                wxOrderRefund.setOperatorUserType(1);
                wxOrderRefund.setOperatTime(new Date());
                if (ret_obj.getInteger("status") == 10000) {
                    wxOrderRefund.setRefundMoney(cashDeposit);
                    wxOrderRefund.setState(1);
                    wxOrderRefund.setTransactionId(ret_obj.getString("transaction_id"));
                    wxOrderRefund.setStateMsg(ret_obj.getString("message"));
                    execute_state_cashDepositState = true;
                } else {
                    if (ret_obj.getInteger("status") == 4001) {
                        execute_state_cashDepositState = false;
                    } else {
                        wxOrderRefund.setState(0);
                        wxOrderRefund.setRefundMoney(new BigDecimal(0));
                        wxOrderRefund.setStateMsg(ret_obj.getString("message"));
                        log.error("总后台同意退款 酷享支付失败，失败原因： " + JsonKit.toJson(ret_obj));
                        execute_state_cashDepositState = false;
                    }
                }
                boolean save = wxOrderRefund.save();
            }
//					WeixinTransferResult transfer = WeixinTransferUtil.transfer(weixinAppConfig.getAppId() , weixinAppConfig.getWxKey() , weixinAppConfig.getWxMchid() ,
//							weixinAppConfig.getKeystoreFilePath() , weixinUser.getOpenid() , agentAccountLog.getId() , weixinUser.getNickname() ,cashDeposit, "代理商审核拒绝");
        } else {
            execute_state_cashDepositState = true;
        }

        Integer controlMoenyState = agent.getControlMoenyState();
        if (controlMoenyState != null && controlMoenyState == 1) {
            //退货款
            BigDecimal controlMoneyAmount = agent.getControlMoneyAmount();

            Order order = Order.dao.findFirst("select * from t_order where type=6 and user_id=?", weixinUser.getId());
            if (order != null) {
                String refund_id = IdGenerateUtils.getOrderId();
                String out_refund_id = null;// 外部退款的流水编号
                boolean execute_state = false;// 执行的状态
                Map<String, String> result_map = null;
                String refund_recv_accout = "微信公众号";
                //普通商品  订单总金额 也就是 退款金额
                BigDecimal total_fee = order.getTotalAmount();
                // 再判断是小程序还是APP
                if (order.getOrderPlatform().equals(1)) { // 小程序支付
                    //判断是普通订单还是预售商品 预售商品需要退款俩次
                    if (order.getType() == 6) { // 货款
                        if (AppGlobal.dev_Mode) {
                            total_fee = new BigDecimal(0.01);
                        }
                        String ret = KusyApi.refund(KusyUtil.Api_key, KusyUtil.Sign_Key, order.getKusyOrderId(), total_fee.doubleValue(), refund_id);
                        JSONObject ret_obj = JSONObject.parseObject(ret);
                        WxOrderRefund wxOrderRefund = new WxOrderRefund();
                        wxOrderRefund.setOrderId(order.getId());
                        wxOrderRefund.setCreateTime(new Date());
                        wxOrderRefund.setType(WxOrderRefund.cancelType_quane);
                        wxOrderRefund.setRefundId(refund_id);
                        wxOrderRefund.setOperator(weixinUser.getId());
                        wxOrderRefund.setOperatorUserType(1);
                        wxOrderRefund.setOperatTime(new Date());
                        log.info("退款:" + JsonKit.toJson(ret_obj));
                        if (ret_obj.getInteger("status") == 10000) {
                            wxOrderRefund.setRefundMoney(controlMoneyAmount);
                            wxOrderRefund.setState(1);
                            wxOrderRefund.setTransactionId(ret_obj.getString("transaction_id"));
                            wxOrderRefund.setStateMsg(ret_obj.getString("message"));
                            execute_state_controlMoneyAmount = true;
                        } else {
                            if (ret_obj.getInteger("status") == 4001) {
                                execute_state_controlMoneyAmount = false;
                            } else {
                                wxOrderRefund.setState(0);
                                wxOrderRefund.setRefundMoney(new BigDecimal(0));
                                wxOrderRefund.setStateMsg(ret_obj.getString("message"));
                                log.error("总后台同意退款 酷享支付失败，失败原因： " + JsonKit.toJson(ret_obj));
                                execute_state_controlMoneyAmount = false;
                            }
                        }
                        boolean save = wxOrderRefund.save();
                        if (save) {
                            order.setRefundRemark("审核不通过退货款!");
                            order.setRefundAmount(controlMoneyAmount);
                            order.update();
                        }

                    }

                }
                if (execute_state) {
                    // 保存账单信息
                    OrderRefund refund = new OrderRefund();
                    refund.setRefundId(refund_id);
                    refund.setOrderId(order.getId());
                    refund.setRefundFee(order.getTotalAmount().intValue() * 100);
//								refund.setItemId(orderItem.getItemId());
                    refund.setRefundRecvAccout(refund_recv_accout);
                    refund.setState(1);
                    refund.setIsAddFreight(0);
                    refund.setOutRefundNo(out_refund_id);
                    refund.save();
                    // 判断订单总数
                    Long item_count = Db.queryLong("select count(1) from t_order_item   where order_id=?", order.getId());
                    order.setRefundAmount(controlMoneyAmount);// 设置订单的退款金额
                    order.setState(OrderState.State_Closed);// 把订单直接完成了
                    order.setModifiedTime(new Date());
                    order.update();
                }

            }
//				AgentAccountLog agentAccountLog = new AgentAccountLog();
//				agentAccountLog.setId(IdGenerateUtils.getId());
//				agentAccountLog.setPrice(controlMoneyAmount);
//				agentAccountLog.setStatus(AgentAccountLog.STATUS_INTO);
//				agentAccountLog.setAccountType(AgentAccountLog.ACCOUNTTYPEYE);
//				agentAccountLog.setAgentId(agent.getId());
//				agentAccountLog.setState(AgentAccountLog.STATEIN);
//				agentAccountLog.setType(AgentAccountLog.TYPE_WITHDRAWAL);
//				agentAccountLog.setCreateTime(new Date());
//				agentAccountLog.save();
//				if(AppGlobal.dev_Mode){
//					controlMoneyAmount = new BigDecimal(0.01);
//				}
//				WeixinTransferResult transfer = WeixinTransferUtil.transfer(weixinAppConfig.getAppId() , weixinAppConfig.getWxKey() , weixinAppConfig.getWxMchid() ,
//						weixinAppConfig.getKeystoreFilePath() , weixinUser.getOpenid() , agentAccountLog.getId() , weixinUser.getNickname() ,controlMoneyAmount, "代理商审核拒绝");
//				if(transfer.isState()){
//					agentAccountLog.setStatus(AgentAccountLog.STATUS_SUCCESS);
//					boolean save = agentAccountLog.save();
//				}
//				log.info("平台打款:" + transfer.getReturn_msg());
        } else {
            execute_state_controlMoneyAmount = true;
        }
        //删除代理商
        if (execute_state_cashDepositState && execute_state_controlMoneyAmount) {
            boolean delete = Agent.dao.deleteById(agent.getId());
            if (delete) {
                weixinUser.setIsAgent(0);
                boolean update = weixinUser.update();
                return new ApiResponse(update, update ? "拒绝操作成功!" : "拒绝操作失败!");
            } else {
                return new ApiResponse(false, "代理商修改失败!");
            }
        } else if (execute_state_cashDepositState && !execute_state_controlMoneyAmount) {
            return new ApiResponse(false, "退款押金失败!");
        } else if (!execute_state_cashDepositState && execute_state_controlMoneyAmount) {
            return new ApiResponse(false, "退款货款失败!");
        } else {
            return new ApiResponse(false, "退款失败!");
        }

    }


    /**
     * 根据 userId 获取信息代理商信息
     *
     * @param userId 用户id
     */
    public Agent findInfoByOpenId(Integer userId) {
        Agent agent = Agent.dao.findInfoByUserId(userId);
        return agent;
    }

    /**
     * 获取购买人属于哪一个代理商
     *
     * @param user
     * @param addressId
     */
    public Map<Integer, Object> detectionUserInAgent(WeixinUser user, Integer addressId) {

        Map<Integer, Object> map = null;
        if (user.getIsAgent() != null && 1 == user.getIsAgent()) {
            Agent agent1 = Agent.dao.findInfoByUserId(user.getId());
            if (agent1 == null) {
                return null;
            }

            if (Agent.TYPE_AREA.equals(agent1.getType())) {
                UserAddress userAddress = UserAddress.dao.findById(addressId);
                AddrCities city = AddrCities.dao.findByCityId(userAddress.getCityId().toString());
                if (city != null) {
                    if (AddrCities.TYPE_OPEN_SUCCESS.equals(city.getIsArea())) {
                        AddrAreas area = AddrAreas.dao.findByAreaId(userAddress.getCountyId().toString());
                        if (area == null) {
                            return null;
                        }
                        Agent agent = Agent.dao.findById(area.getAgentId());
                        if (agent == null) {
                            return null;
                        }
                        AgentCity agentCity = AgentCity.dao.findByAgentIdAndAreaId(agent.getId(), area.getAreaid());
                        map = new HashMap<>();
                        map.put(0, agent);
                        map.put(1, agentCity);
                        return map;
                    } else {
                        Integer cityAgentId = city.getAgentId();
                        Agent agent = Agent.dao.findById(cityAgentId);
                        if (agent == null) {
                            return null;
                        }
                        AgentCity agentCity = AgentCity.dao.findByCityIdAndAgentId(agent.getId(), city.getCityid());
                        map = new HashMap<>();
                        map.put(0, agent);
                        map.put(1, agentCity);
                        return map;
                    }
                }
            }
            map = new HashMap<>();
            map.put(0, agent1);
            return map;
        }
        if (user.getExtensionId() != null) {
            Agent agent1 = Agent.dao.findById(user.getExtensionId());
            if (Agent.TYPE_AREA.equals(agent1.getType())) {
                UserAddress userAddress = UserAddress.dao.findById(addressId);
                AddrCities city = AddrCities.dao.findByCityId(userAddress.getCityId().toString());
                if (city != null) {
                    if (AddrCities.TYPE_OPEN_SUCCESS.equals(city.getIsArea())) {
                        AddrAreas area = AddrAreas.dao.findByAreaId(userAddress.getCountyId().toString());
                        if (area == null) {
                            return null;
                        }
                        Agent agent = Agent.dao.findById(area.getAgentId());
                        if (agent == null) {
                            return null;
                        }
                        AgentCity agentCity = AgentCity.dao.findByAgentIdAndAreaId(agent.getId(), area.getAreaid());
                        map = new HashMap<>();
                        map.put(0, agent);
                        map.put(1, agentCity);
                        return map;
                    } else {
                        Integer cityAgentId = city.getAgentId();
                        Agent agent = Agent.dao.findById(cityAgentId);
                        if (agent == null) {
                            return null;
                        }
                        AgentCity agentCity = AgentCity.dao.findByCityIdAndAgentId(agent.getId(), city.getCityid());
                        map = new HashMap<>();
                        map.put(0, agent);
                        map.put(1, agentCity);
                        return map;
                    }
                }
            } else {
                map = new HashMap<>();
                map.put(0, agent1);
            }

            return map;
        } else {
//			String cityId = addressId;
            UserAddress userAddress = UserAddress.dao.findById(addressId);
            AddrCities city = AddrCities.dao.findByCityId(userAddress.getCityId().toString());
            if (city != null) {
                if (AddrCities.TYPE_OPEN_SUCCESS.equals(city.getIsArea())) {
                    AddrAreas area = AddrAreas.dao.findByAreaId(user.getAreaId());
                    if (area == null) {
                        return null;
                    }
                    Agent agent = Agent.dao.findById(area.getAgentId());
                    if (agent == null) {
                        return null;
                    }
                    AgentCity agentCity = AgentCity.dao.findByAgentIdAndAreaId(agent.getId(), area.getAreaid());
                    map = new HashMap<>();
                    map.put(0, agent);
                    map.put(1, agentCity);
                    return map;
                } else {
                    Integer cityAgentId = city.getAgentId();
                    Agent agent = Agent.dao.findById(cityAgentId);
                    if (agent == null) {
                        return null;
                    }
                    AgentCity agentCity = AgentCity.dao.findByCityIdAndAgentId(agent.getId(), city.getCityid());
                    map = new HashMap<>();
                    map.put(0, agent);
                    map.put(1, agentCity);
                    return map;
                }
            }
        }
        return map;
    }

    public ApiResponse findByUser(WeixinUser user) {
        Agent agent = Agent.dao.findInfoByUserId(user.getId());
//		Agent agent = Agent.dao.findById(id);
        if (agent != null) {


            //当月盈利
            SQLUtils monthSql = new SQLUtils();
            monthSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id in ( ");
            monthSql.append(" select ag.id from t_agent ag where ag.parent_id=?) AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%Y%m')=date_format(CurDate(),'%Y%m')");
            //当月销售
            SQLUtils monthOrderSql = new SQLUtils();
            monthOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where log.agent_id in ( ");
            monthOrderSql.append(" select ag.id from t_agent ag where ag.parent_id=?) AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%Y%m')=date_format(CurDate(),'%Y%m')");
            //当年盈利
            SQLUtils yearSql = new SQLUtils();
            yearSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id in ( ");
            yearSql.append(" select ag.id from t_agent ag where ag.parent_id=?) AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate())  ");
            //当年销售
            SQLUtils yearOrderSql = new SQLUtils();
            yearOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where log.agent_id in ( ");
            yearOrderSql.append(" select ag.id from t_agent ag where ag.parent_id=?) AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate()) ");

            BigDecimal monthPrice = Db.queryBigDecimal(monthSql.toString(), agent.getId());
            BigDecimal monthOrderPrice = Db.queryBigDecimal(monthOrderSql.toString(), agent.getId());
            BigDecimal yearPrice = Db.queryBigDecimal(yearSql.toString(), agent.getId());
            BigDecimal yearOrderPrice = Db.queryBigDecimal(yearOrderSql.toString(), agent.getId());

            agent.put("monthPrice", monthPrice);
            agent.put("monthOrderPrice", monthOrderPrice);
            agent.put("yearPrice", yearPrice);
            agent.put("yearOrderPrice", yearOrderPrice);

            /*直客相关数据*/
            SQLUtils zikeMonthSql = new SQLUtils();
            zikeMonthSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id=? and is_son_order<>1 ");
            zikeMonthSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y%m')=date_format(CurDate(),'%Y%m')");

            SQLUtils zikeMonthOrderSql = new SQLUtils();
            zikeMonthOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where log.agent_id=? and is_son_order<>1 ");
            zikeMonthOrderSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y%m')=date_format(CurDate(),'%Y%m')");

            SQLUtils zikeYearSql = new SQLUtils();
            zikeYearSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id=? and is_son_order<>1 ");
            zikeYearSql.append("  AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate()) ");

            SQLUtils zikeYearOrderSql = new SQLUtils();
            zikeYearOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where log.agent_id=? and is_son_order<>1");
            zikeYearOrderSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate()) ");

            BigDecimal zikeMonthPrice = Db.queryBigDecimal(zikeMonthSql.toString(), agent.getId());
            BigDecimal zikeMonthOrderPrice = Db.queryBigDecimal(zikeMonthOrderSql.toString(), agent.getId());
            BigDecimal zikeYearPrice = Db.queryBigDecimal(zikeYearSql.toString(), agent.getId());
            BigDecimal zikeYearOrderPrice = Db.queryBigDecimal(zikeYearOrderSql.toString(), agent.getId());

            agent.put("zikeMonthPrice", zikeMonthPrice);
            agent.put("zikeMonthOrderPrice", zikeMonthOrderPrice);
            agent.put("zikeYearPrice", zikeYearPrice);
            agent.put("zikeYearOrderPrice", zikeYearOrderPrice);



            /*特约经销商数据*/
            SQLUtils jinXiaoShangMonthSql = new SQLUtils();
            jinXiaoShangMonthSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id=? and is_son_order=1 ");
            jinXiaoShangMonthSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y%m')=date_format(CurDate(),'%Y%m')");

            SQLUtils jinXiaoShangMonthOrderSql = new SQLUtils();
            jinXiaoShangMonthOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where log.agent_id=? and is_son_order=1 ");
            jinXiaoShangMonthOrderSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y%m')=date_format(CurDate(),'%Y%m')");

            SQLUtils jinXiaoShangYearSql = new SQLUtils();
            jinXiaoShangYearSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id=? and is_son_order=1 ");
            jinXiaoShangYearSql.append("  AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate()) ");

            SQLUtils jinXiaoShangYearOrderSql = new SQLUtils();
            jinXiaoShangYearOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where log.agent_id=? and is_son_order=1");
            jinXiaoShangYearOrderSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate()) ");

            BigDecimal jinXiaoShangMonthPrice = Db.queryBigDecimal(jinXiaoShangMonthSql.toString(), agent.getId());
            BigDecimal jinXiaoShangMonthOrderPrice = Db.queryBigDecimal(jinXiaoShangMonthOrderSql.toString(), agent.getId());
            BigDecimal jinXiaoShangYearPrice = Db.queryBigDecimal(jinXiaoShangYearSql.toString(), agent.getId());
            BigDecimal jinXiaoShangYearOrderPrice = Db.queryBigDecimal(jinXiaoShangYearOrderSql.toString(), agent.getId());

            agent.put("jinXiaoShangMonthPrice", jinXiaoShangMonthPrice);
            agent.put("jinXiaoShangMonthOrderPrice", jinXiaoShangMonthOrderPrice);
            agent.put("jinXiaoShangYearPrice", jinXiaoShangYearPrice);
            agent.put("jinXiaoShangYearOrderPrice", jinXiaoShangYearOrderPrice);

            /*总数据*/
            SQLUtils allMonthSql = new SQLUtils();
            allMonthSql.append(" select sum(price) as price from t_agent_account_log log where  ");
            allMonthSql.append(" log.agent_id=?  ");
            allMonthSql.append(" AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%Y%m')=date_format(CurDate(),'%Y%m') ");

            SQLUtils allMonthOrderSql = new SQLUtils();
            allMonthOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where  ");
            allMonthOrderSql.append(" log.agent_id=? ");
            allMonthOrderSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y%m')=date_format(CurDate(),'%Y%m')");

            SQLUtils allYearSql = new SQLUtils();
            allYearSql.append(" select sum(price) as price from t_agent_account_log log where   ");
            allYearSql.append("  log.agent_id=?  ");
            allYearSql.append("  AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate()) ");

            SQLUtils allYearOrderSql = new SQLUtils();
            allYearOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where ");
            allYearOrderSql.append(" log.agent_id=?  ");
            allYearOrderSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate()) ");

            BigDecimal allMonthPrice = Db.queryBigDecimal(allMonthSql.toString(), agent.getId());
            BigDecimal allMonthOrderPrice = Db.queryBigDecimal(allMonthOrderSql.toString(), agent.getId());
            BigDecimal allYearPrice = Db.queryBigDecimal(allYearSql.toString(), agent.getId());
            BigDecimal allYearOrderPrice = Db.queryBigDecimal(allYearOrderSql.toString(), agent.getId());

            System.out.println("当月盈利:" + monthPrice + ",当月销售:" + monthOrderPrice);
            System.out.println("当年盈利:" + yearPrice + ",当年销售:" + yearOrderPrice);
            System.out.println("直客当月盈利:" + zikeMonthPrice + ",直客当月销售:" + zikeMonthOrderPrice);
            System.out.println("直客当年盈利:" + zikeYearPrice + ",直客当年销售:" + zikeYearOrderPrice);
            System.out.println("经销商当月盈利:" + jinXiaoShangMonthPrice + ",经销商当月销售:" + jinXiaoShangMonthOrderPrice);
            System.out.println("经销商当年盈利:" + jinXiaoShangYearPrice + ",经销商当年销售:" + jinXiaoShangYearOrderPrice);
            System.out.println("总体当月盈利:" + allMonthPrice + ",总体当月销售:" + allMonthOrderPrice);
            System.out.println("总体当年盈利:" + allYearPrice + ",总体当年销售:" + allYearOrderPrice);

            agent.put("allMonthPrice", allMonthPrice);
            agent.put("allMonthOrderPrice", allMonthOrderPrice);
            agent.put("allYearPrice", allYearPrice);
            agent.put("allYearOrderPrice", allYearOrderPrice);


            SQLUtils zhiKeLeiJiSql = new SQLUtils();
            zhiKeLeiJiSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id=? and log.is_son_order<>1");
            zhiKeLeiJiSql.append(" AND log.`status`=1  AND log.price<>0 and log.state=1 ");
            SQLUtils zhiKeLeiJiOrderSql = new SQLUtils();
            zhiKeLeiJiOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where  log.agent_id=? and log.is_son_order<>1 ");
            zhiKeLeiJiOrderSql.append("  AND log.`status`=1  AND log.price<>0 and log.state=1 ");

            SQLUtils jinXiaoLeiJiSql = new SQLUtils();
            jinXiaoLeiJiSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id=? and log.is_son_order=1 ");
            jinXiaoLeiJiSql.append("  AND log.`status`=1  AND log.price<>0 and log.state=1  ");
            SQLUtils jinXiaoLeiJiOrderSql = new SQLUtils();
            jinXiaoLeiJiOrderSql.append(" select sum(order_price) as price from t_agent_account_log log  where log.agent_id=? and log.is_son_order=1 ");
            jinXiaoLeiJiOrderSql.append("  AND log.`status`=1  AND log.price<>0 and log.state=1  ");

            BigDecimal zhiKeLeiJiPrice = Db.queryBigDecimal(zhiKeLeiJiSql.toString(), agent.getId());
            BigDecimal zhiKeLeiJiOrderPrice = Db.queryBigDecimal(zhiKeLeiJiOrderSql.toString(), agent.getId());
            BigDecimal jinXiaoLeiJiPrice = Db.queryBigDecimal(jinXiaoLeiJiSql.toString(), agent.getId());
            BigDecimal jinXiaoLeiJiOrderPrice = Db.queryBigDecimal(jinXiaoLeiJiOrderSql.toString(), agent.getId());

            agent.put("zhiKeLeiJiPrice", zhiKeLeiJiPrice);
            agent.put("zhiKeLeiJiOrderPrice", zhiKeLeiJiOrderPrice);
            agent.put("jinXiaoLeiJiPrice", jinXiaoLeiJiPrice);
            agent.put("jinXiaoLeiJiOrderPrice", jinXiaoLeiJiOrderPrice);
            if (Agent.TYPE_ER.equals(agent.getType())) {
                /*累计下单人数*/
                Long orderUserCount = Db.queryLong("select  COUNT(distinct  o.user_id) FROM  t_order o left join t_agent ag on ag.id=o.agent_id WHERE (ag.id=? or ag.parent_id=?)  and o.state=3 ", agent.getId(), agent.getId());
                agent.put("orderUserCount", orderUserCount);
                System.out.println("累计下单人数:" + orderUserCount);
            } else if (Agent.TYPE_AREA.equals(agent.getType())) {
                /*累计下单人数*/
                SQLUtils leiji = new SQLUtils();
                leiji.append(" select  COUNT(distinct  o.user_id) FROM  t_order o ");
                leiji.append(" LEFT JOIN t_user_address address on address.id=o.address_id  ");
                leiji.append(" LEFT JOIN t_addr_cities city on city.cityid=address.city_id  ");
                leiji.append(" LEFT JOIN t_addr_areas area on area.areaid=address.county_id  ");
                leiji.append(" left join t_agent agCity on agCity.id=city.agent_id  ");
                leiji.append(" LEFT JOIN t_agent agCounty  on agCounty.id=area.agent_id  ");
                leiji.append(" LEFT JOIN t_agent agorder on agorder.id= o.agent_id ");
                leiji.append(" WHERE (agCity.id=? or agCity.parent_id=? or agCounty.id=? or agCounty.parent_id=? or agorder.id=? or agorder.parent_id=?)  and o.state=3  ");
                Long orderUserCount = Db.queryLong(leiji.toString(), agent.getId(), agent.getId(), agent.getId(), agent.getId(), agent.getId(), agent.getId());
                agent.put("orderUserCount", orderUserCount);
                System.out.println("累计下单人数:" + orderUserCount);
            }
        }
        return new ApiResponse(true, "success", agent);
    }

    /**
     * 充值
     *
     * @param price
     * @param id
     * @return
     */
    public ApiResponse recharge(String price, Integer id) {
        if (StringUtil.isBlank(price)) {
            return new ApiResponse(false, "充值金额不能为null!");
        }
        BigDecimal rechargePrice = new BigDecimal(0.00);
        try {
            rechargePrice = new BigDecimal(price);
        } catch (NumberFormatException e) {
            return new ApiResponse(false, "金额输出错误");
        }
        AgentCity agentCity = AgentCity.dao.findById(id);
        if (agentCity == null) {
            return new ApiResponse(false, "该城市未找到该代理商,请联系管理员查证!");
        }
        Agent agent = Agent.dao.findById(agentCity.getAgentId());
        if (agent == null) {
            return new ApiResponse(false, "代理商信息错误!");
        }
        BigDecimal icePrice = agentCity.getIcePrice();
        if (icePrice == null) {
            icePrice = new BigDecimal(0.00);
        }
        agentCity.setIcePrice(icePrice.add(rechargePrice));
        boolean agentCityUpdate = agentCity.update();
        if (agentCityUpdate) {
            BigDecimal productPrice = agent.getProductPrice();
            if (productPrice == null) {
                productPrice = new BigDecimal(0.00);
            }
            agent.setProductPrice(productPrice.add(rechargePrice));
            agent.update();
            AgentAccountLog agentAccountLog = new AgentAccountLog();
            agentAccountLog.setId(IdGenerateUtils.getId());
            agentAccountLog.setStatus(1);
            agentAccountLog.setPrice(productPrice);
            agentAccountLog.setCreateTime(new Date());
            agentAccountLog.setAgentId(agent.getId());
            agentAccountLog.setType(AgentAccountLog.TYPE_RECHARGE);
            agentAccountLog.setState(AgentAccountLog.STATEIN);
            agentAccountLog.setAccountType(AgentAccountLog.ACCOUNTTYPEYE);
            agentAccountLog.save();
        }
        return new ApiResponse(agentCityUpdate, agentCityUpdate ? "操作成功!" : "操作失败!");
    }


    /**
     * 获取代理商的流水记录
     *
     * @param page
     * @param size
     * @param agentId 代理商id
     * @param state   状态(充值还是提现)
     */
    public Page<AgentAccountLog> findAccountLogList(int page, int size, String agentId, Integer state) {
//		Agent agent = Agent.dao.findById(agentId);
//		if(agent.getType()==Agent.TYPE_ER){
//			Page<AgentAccountLog> accountLogList = AgentAccountLog.dao.findAccountLogErJiList(page , size , agentId , state,1);
//			List<AgentAccountLog> accountLogListList = accountLogList.getList();
//			for (AgentAccountLog agentAccountLog : accountLogListList) {
//				if(agentAccountLog.getOrderId()!=null){
//					agentAccountLog.put("item", OrderItem.dao.getItembyId(agentAccountLog.getOrderId()));
//				}
//			}
//			return accountLogList;
//		}else{
        Page<AgentAccountLog> accountLogList = AgentAccountLog.dao.findAccountLogList(page, size, agentId, state, 1);
        List<AgentAccountLog> accountLogListList = accountLogList.getList();
        for (AgentAccountLog agentAccountLog : accountLogListList) {
            if (agentAccountLog.getOrderId() != null) {
                agentAccountLog.put("item", OrderItem.dao.getItembyId(agentAccountLog.getOrderId()));
            }
        }
        return accountLogList;
//		}


    }

    /**
     * 保存用户提现申请
     *
     * @param price
     * @param bankName
     * @param bankUserName
     * @param bankNum
     */
    public ApiResponse withdrawal(String price, Integer userId, String bankName, String bankUserName, String bankNum) {
        if (StringUtil.isBlank(price)) {
            return new ApiResponse(false, "提现金额不能为null!");
        }
        BigDecimal withdrawalPrice = new BigDecimal(0.00);
        try {
            withdrawalPrice = new BigDecimal(price);
        } catch (NumberFormatException e) {
            return new ApiResponse(false, "金额输出错误");
        }
        if (withdrawalPrice.compareTo(new BigDecimal(0.00)) != 1) {
            return new ApiResponse(false, "提现金额必须大于0元");
        }
        Agent agent = Agent.dao.findInfoByUserId(userId);
        BigDecimal agentPrice = agent.getPrice();
        if (agentPrice == null) {
            agentPrice = new BigDecimal(0.00);
        }
        if (withdrawalPrice.compareTo(agentPrice) > 0) {
            return new ApiResponse(false, "提现金额大于剩余金额,提现失败!");
        }
//		if(StringUtil.isBlank(bankName)||StringUtil.isBlank(bankUserName)||StringUtil.isBlank(bankNum)){
//			return new ApiResponse(false,"银行卡信息必填!");
//		}

        BigDecimal iceprice = agent.getIceprice();
        if (iceprice == null) {
            iceprice = new BigDecimal(0.00);
        }
        agent.setIceprice(iceprice.add(withdrawalPrice));
        agent.setPrice(agentPrice.subtract(withdrawalPrice));
        agent.update();
        AgentAccountLog agentAccountLog = new AgentAccountLog();
        agentAccountLog.setId(IdGenerateUtils.getId());
        agentAccountLog.setPrice(withdrawalPrice);
        agentAccountLog.setStatus(2);
        agentAccountLog.setAccountType(AgentAccountLog.ACCOUNTTYPEYE);
        agentAccountLog.setAgentId(agent.getId());
        agentAccountLog.setState(AgentAccountLog.STATEOUT);
        agentAccountLog.setType(AgentAccountLog.TYPE_WITHDRAWAL);
        agentAccountLog.setCreateTime(new Date());
        agentAccountLog.setBankUserName(bankUserName);
        agentAccountLog.setBankNum(bankNum);
        agentAccountLog.setBankName(bankName);
        boolean save = agentAccountLog.save();
        return new ApiResponse(save, save ? "提现申请成功!" : "提现申请失败!");
    }


    /**
     * 特约经销商提现
     *
     * @param price
     * @param bankName
     * @param bankUserName
     * @param bankNum
     */
    public ApiResponse authorizedDealerWithdrawal(String price, Integer userId, String bankName, String bankUserName, String bankNum, String agentId) {
        if (StringUtil.isBlank(price)) {
            return new ApiResponse(false, "提现金额不能为null!");
        }
        BigDecimal withdrawalPrice = new BigDecimal(0.00);
        try {
            withdrawalPrice = new BigDecimal(price);
        } catch (NumberFormatException e) {
            return new ApiResponse(false, "金额输出错误");
        }
        if (withdrawalPrice.compareTo(new BigDecimal(0.00)) != 1) {
            return new ApiResponse(false, "提现金额必须大于0元");
        }
        Agent agent = Agent.dao.findById(agentId);
        BigDecimal agentPrice = agent.getPrice();
        if (agentPrice == null) {
            agentPrice = new BigDecimal(0.00);
        }
        if (withdrawalPrice.compareTo(agentPrice) > 0) {
            return new ApiResponse(false, "提现金额大于剩余金额,提现失败!");
        }
        BigDecimal iceprice = agent.getIceprice();
        if (iceprice == null) {
            iceprice = new BigDecimal(0.00);
        }
        agent.setIceprice(iceprice.add(withdrawalPrice));
        agent.setPrice(agentPrice.subtract(withdrawalPrice));
        agent.update();
        AgentAccountLog agentAccountLog = new AgentAccountLog();
        agentAccountLog.setId(IdGenerateUtils.getId());
        agentAccountLog.setPrice(withdrawalPrice);
        agentAccountLog.setStatus(AgentAccountLog.STATUS_SUCCESS);
        agentAccountLog.setAccountType(AgentAccountLog.ACCOUNTTYPEYE);
        agentAccountLog.setAgentId(agent.getId());
        agentAccountLog.setState(AgentAccountLog.STATEOUT);
        agentAccountLog.setType(AgentAccountLog.TYPE_WITHDRAWAL);
        agentAccountLog.setCreateTime(new Date());
        agentAccountLog.setBankUserName(bankUserName);
        agentAccountLog.setBankNum(bankNum);
        agentAccountLog.setBankName(bankName);
        agentAccountLog.setOptionTime(new Date());
        boolean save = agentAccountLog.save();
        return new ApiResponse(save, save ? "提现申请成功!" : "提现申请失败!");
    }

    /**
     * 流水操作总记录
     *
     * @param agentId
     * @return
     */
    public ApiResponse accountLogAll(String agentId) {
        Agent agent = Agent.dao.findById(agentId);
        if (agent == null) {
            return new ApiResponse(false, "代理商不存在!");
        }
        List<AgentCity> agentCityList = AgentCity.dao.findByAgentId(agent.getId(), AgentCity.STATUS_SUCCESS);
        agent.put("agentCity", agentCityList);
        return new ApiResponse(true, "success", agent);
    }


    /**
     * 推送时计算
     *
     * @param agentCityId 代理商代理城市id
     * @param price       订单货款
     * @param orderId     订单编号
     * @return
     */
    public Map<String, BigDecimal> pushOrderProfit(Integer agentId, Integer agentCityId, BigDecimal price, String orderId) {
        if (StringUtil.isBlank(orderId)) {
            return null;
        }
        Agent agent = Agent.dao.findById(agentId);
        if (agent == null) {
            return null;
        }
        //二级代理商

        if (Agent.TYPE_ER.equals(agent.getType())) {
            Map<String, BigDecimal> map = new HashMap<>();
            AgentLevel agentLevel = AgentLevel.dao.findById(agent.getLevelId());
            BigDecimal erjiAgentDiscount = agentLevel.getDiscount();
            BigDecimal bigDecimal = addAreaAgentPrice111(agent, orderId, price, erjiAgentDiscount);
            BigDecimal agentPrice = other111(agent, orderId, price, erjiAgentDiscount, AgentAccountLog.TEYUE_FALSE, null, null);
            map.put("agent", bigDecimal);
            map.put("parent", null);
            map.put("area", agentPrice);
            return map;

        } else if (Agent.TYPE_TEYUE.equals(agent.getType())) {
            Map<String, BigDecimal> map = new HashMap<>();
            BigDecimal discount = agent.getDiscount();
            BigDecimal agentPrice = other111(agent, orderId, price, discount, AgentAccountLog.TEYUE_FALSE, null, null);
            ApiResponse other1 = new ApiResponse(false, "");
            map.put("agent", agentPrice);
            BigDecimal erjiAgentDiscount = new BigDecimal(0.00);
            if (agent.getParentId() != null) {
                Agent parentAgent = Agent.dao.findById(agent.getParentId());
                AgentLevel agentLevel = null;
                if (parentAgent != null && Agent.TYPE_ER.equals(parentAgent.getType())) {
                    agentLevel = AgentLevel.dao.findById(parentAgent.getLevelId());
                } else {
                    List<AgentCity> cities = AgentCity.dao.findByAgentId(parentAgent.getId(), Agent.STATUS_SUCCESS);
                    if (cities != null && cities.size() > 0) {
                        AgentCity agentCity = cities.get(0);
                        agentLevel = AgentLevel.dao.findById(agentCity.getLevelId());
                    }
                }
                erjiAgentDiscount = agentLevel.getDiscount();
                //每单的利润
                BigDecimal profits = price.subtract(price.multiply(discount));
                BigDecimal bigDecimal = other111(parentAgent, orderId, price, erjiAgentDiscount, AgentAccountLog.TEYUE_TRUE, agent.getId(), profits);
                map.put("parent", bigDecimal);
            }
            BigDecimal areaAgentPrice = addAreaAgentPrice111(agent, orderId, price, erjiAgentDiscount);
            map.put("area", areaAgentPrice);
            return map;
        } else if (Agent.TYPE_NORM.equals(agent.getType())) {
            Map<String, BigDecimal> map = new HashMap<>();
            AgentLevel agentLevel = AgentLevel.dao.findById(agent.getLevelId());
            BigDecimal discount = agentLevel.getDiscount();
            BigDecimal putongPrice = addAreaAgentPrice111(agent, orderId, price, discount);
            BigDecimal quyuPrice = other111(agent, orderId, price, discount, AgentAccountLog.TEYUE_FALSE, null, null);
            map.put("agent", putongPrice);
            map.put("parent", null);
            map.put("area", quyuPrice);
            return map;


        } else if (Agent.TYPE_AREA.equals(agent.getType())) {
            Map<String, BigDecimal> map = new HashMap<>();
            AgentCity agentCity = AgentCity.dao.findById(agentCityId);
            if (agentCity == null) {
                return null;
            }
            if (agentCity.getAgentId() == null) {
                return null;
            }
            AgentLevel agentLevel = AgentLevel.dao.findById(agentCity.getLevelId());
            BigDecimal discount = agentLevel.getDiscount();
            BigDecimal orderPrice = price.multiply(discount);
            //每单的利润
            BigDecimal profits = price.subtract(orderPrice);
            map.put("agent", profits);
            map.put("parent", null);
            map.put("area", null);
            return map;
        } else {
            return null;
        }
    }

    /**
     * 给区域代理商添加金额
     */
    public BigDecimal addAreaAgentPrice111(Agent otherAgent, String orderId, BigDecimal price, BigDecimal otherDiscount) {

//		BigDecimal otherDiscount = otherAgent.getDiscount();
        BigDecimal otherOrderPrice = price.multiply(otherDiscount);
        //每单的利润
        BigDecimal otherProfits = price.subtract(otherOrderPrice);
        Order order = Order.dao.findById(orderId);
        Integer addressId = order.getAddressId();
        UserAddress userAddress = UserAddress.dao.findById(addressId);
        AgentCity agentCity = AgentCity.dao.findByCityId(userAddress.getCityId());
        if (agentCity == null) {
            return null;
        }
        Agent agent = Agent.dao.findById(agentCity.getAgentId());
        AgentLevel agentLevel = AgentLevel.dao.findById(agentCity.getLevelId());
        if (agentLevel == null) {
            return null;
        }
        BigDecimal discount = agentLevel.getDiscount();
        BigDecimal orderPrice = price.multiply(discount);
        BigDecimal profits = price.subtract(orderPrice).subtract(otherProfits);
        return profits;
    }

    public BigDecimal other111(Agent agent, String orderId, BigDecimal price, BigDecimal discount, Integer isSon, Integer sonAgentId, BigDecimal teyeAgentPrice) {
        BigDecimal orderPrice = price.multiply(discount);
        //每单的利润
        BigDecimal profits = price.subtract(orderPrice);

        return profits;
    }


    /**
     * 订单完成后给供应商添加金额
     *
     * @param agentCityId 代理商代理城市id
     * @param
     * @return
     */
    @Before({Tx.class})
    public ApiResponse fashionable(Integer agentId, Integer agentCityId, Order o) {
        BigDecimal couponAmount = o.getCouponAmount();
        if (couponAmount == null) {
            couponAmount = new BigDecimal(0.0D);
        }
        BigDecimal erjiPrices = new BigDecimal(0.0D);
        BigDecimal teyuePrices = new BigDecimal(0.0D);
        BigDecimal quyuPices = new BigDecimal(0.0D);
        List<OrderItem> items = OrderItem.dao.findOrderItemByOrderId(o.getId());
        Integer sumProduct = Integer.valueOf(0);
        for (Iterator localIterator = items.iterator(); localIterator.hasNext(); ) {
            OrderItem item = (OrderItem) localIterator.next();
            if (item.getIsGifts().intValue() == 0) {
                sumProduct = Integer.valueOf(sumProduct.intValue() + item.getNums().intValue());
            }
        }
//		OrderItem item;
        BigDecimal divide = new BigDecimal(0.0D);
        if (sumProduct.intValue() != 0) {
            divide = couponAmount.divide(new BigDecimal(sumProduct.intValue()), 2);
        }
        for (OrderItem item : items) {
            if (item.getIsGifts().intValue() == 0) {
                Integer productId = item.getProductId();
                Products products = (Products) Products.dao.findById(productId);
                if (products != null) {
                    BigDecimal erjiPrice = products.getErjiPrice();
                    if (erjiPrice == null) {
                        erjiPrice = new BigDecimal(0.0D);
                    }
                    BigDecimal teyuePrice = products.getTeyuePrice();
                    if (teyuePrice == null) {
                        teyuePrice = new BigDecimal(0.0D);
                    }
                    BigDecimal quyuPrice = products.getQuyuPrice();
                    if (quyuPrice == null) {
                        quyuPrice = new BigDecimal(0.0D);
                    }
                    BigDecimal erjiItemPrice = erjiPrice.multiply(item.getPrice().subtract(divide));
                    BigDecimal teyueItemPrice = teyuePrice.multiply(item.getPrice().subtract(divide));
                    BigDecimal quyuItemPrice = quyuPrice.multiply(item.getPrice().subtract(divide));
                    erjiPrices = erjiPrices.add(erjiItemPrice);
                    teyuePrices = teyuePrices.add(teyueItemPrice);
                    quyuPices = quyuPices.add(quyuItemPrice);
                }
            }
        }
        if (StringUtil.isBlank(o.getId())) {
            return new ApiResponse(false, "����id������null");
        }
        Agent agent = (Agent) Agent.dao.findById(agentId);
        if (agent == null) {
            return new ApiResponse(false, "������������!");
        }
        ApiResponse apiResponse = diguiAgent(agent, items, null, new BigDecimal(0.0D), o, AgentAccountLog.TEYUE_FALSE, new BigDecimal(0.0D), new BigDecimal(0.0D));
        BigDecimal profits = (BigDecimal) apiResponse.getData();
        ApiResponse apiResponse1 = areaAgentAddPrice(o, profits);
        if (o.getUserId() != null) {
            WeixinUser weixinUser = (WeixinUser) WeixinUser.dao.findById(o.getUserId());
            if (weixinUser.getIsAgent().intValue() == 1) {
                Agent infoByUserId = Agent.dao.findInfoByUserId(weixinUser.getId());
                if ((!agent.getId().equals(infoByUserId.getId())) && (agent.getId().equals(infoByUserId.getParentId()))) {
                    BigDecimal orderProfits = new BigDecimal(0.0D);
                    if ((apiResponse1 != null) && (apiResponse1.getData() != null)) {
                        orderProfits = profits.add((BigDecimal) apiResponse1.getData());
                    } else {
                        orderProfits = profits;
                    }
                    BigDecimal subtract = o.getTotalAmount().subtract(orderProfits);
                    BigDecimal netSalesAll = agent.getNetSalesAll();
                    if (netSalesAll == null) {
                        netSalesAll = new BigDecimal(0.0D);
                    }
                    agent.setNetSalesAll(netSalesAll.add(subtract));
                    agent.update();
                }
            } else if ((weixinUser.getExtensionId() != null) && (agent.getId().equals(weixinUser.getExtensionId()))) {
                BigDecimal orderProfits = new BigDecimal(0.0D);
                if ((apiResponse1 != null) && (apiResponse1.getData() != null)) {
                    orderProfits = profits.add((BigDecimal) apiResponse1.getData());
                } else {
                    orderProfits = profits;
                }
                BigDecimal subtract = o.getTotalAmount().subtract(orderProfits);
                BigDecimal netSalesAll = agent.getNetSalesAll();
                if (netSalesAll == null) {
                    netSalesAll = new BigDecimal(0.0D);
                }
                agent.setNetSalesAll(netSalesAll.add(subtract));
                agent.update();
            }
        }
        return apiResponse;
    }

    private ApiResponse diguiAgent(Agent agent, List<OrderItem> items, Integer sonAgentId, BigDecimal sonAgentPrice, Order order, Integer isSon, BigDecimal sonNetSales, BigDecimal orderProfits) {
        if (agent.getStatus().intValue() == 99) {
            return new ApiResponse();
        }
        BigDecimal activityPrice = new BigDecimal(0.0D);
        Integer activityProductSkuId = null;
        Integer activityProductId = null;

        BigDecimal agentDecimal = new BigDecimal(0.0D);
        BigDecimal profits = new BigDecimal(0.0D);
        Integer isTEYUE = AgentAccountLog.TEYUE_FALSE;
        BigDecimal netSales = new BigDecimal(0.0D);

        BigDecimal couponAmount = order.getCouponAmount();
        if (couponAmount == null) {
            couponAmount = new BigDecimal(0.0D);
        }
        List<OrderItem> sumProductItems = OrderItem.dao.findOrderItemByOrderId(order.getId());
        Integer sumProduct = Integer.valueOf(0);
        for (Iterator localIterator = sumProductItems.iterator(); localIterator.hasNext(); ) {
            OrderItem item = (OrderItem) localIterator.next();
            if (item.getIsGifts().intValue() == 0) {
                sumProduct = Integer.valueOf(sumProduct.intValue() + item.getNums().intValue());
            }
        }
        BigDecimal divide = new BigDecimal(0.0D);
        if (sumProduct.intValue() != 0) {
            divide = couponAmount.divide(new BigDecimal(sumProduct.intValue()), 2);
        }
        if (Agent.TYPE_NORM.equals(agent.getType())) {
            for (OrderItem item : items) {
                if (item.getIsGifts().intValue() != 1) {
                    Integer productId = item.getProductId();
                    Products product = (Products) Products.dao.findById(productId);
                    if (product != null) {
                        BigDecimal normPrice = product.getNormPrice();
                        if (normPrice == null) {
                            normPrice = new BigDecimal(0.0D);
                        }
                        BigDecimal profitsItem = new BigDecimal(1).subtract(product.getNormPrice().multiply(new BigDecimal(0.01D)));
                        BigDecimal proNetSales = product.getNormPrice().multiply(new BigDecimal(0.01D));
                        BigDecimal itemPrice = item.getPrice().subtract(divide);
                        if ((activityPrice != null) &&
                                (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                                (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                            itemPrice = itemPrice.subtract(activityPrice);
                        }
                        BigDecimal multiply = itemPrice.multiply(profitsItem);
                        if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                            multiply = multiply.multiply(item.getDiscount());
                            proNetSales = proNetSales.multiply(item.getDiscount());
                        }
                        netSales = netSales.add(proNetSales);
                        agentDecimal = agentDecimal.add(multiply);
                    }
                }
            }
        } else if (Agent.TYPE_TEYUE.equals(agent.getType())) {
            for (OrderItem item : items) {
                if (item.getIsGifts().intValue() != 1) {
                    Integer productId = item.getProductId();
                    Products product = (Products) Products.dao.findById(productId);
                    BigDecimal teyuePrice = product.getTeyuePrice();
                    if (teyuePrice == null) {
                        teyuePrice = new BigDecimal(0.0D);
                    }
                    if (product != null) {
                        BigDecimal profitsItem = new BigDecimal(1).subtract(teyuePrice.multiply(new BigDecimal(0.01D)));
                        BigDecimal proNetSales = teyuePrice.multiply(new BigDecimal(0.01D));
                        BigDecimal itemPrice = item.getPrice().subtract(divide);
                        if ((activityPrice != null) &&
                                (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                                (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                            itemPrice = itemPrice.subtract(activityPrice);
                        }
                        BigDecimal multiply = itemPrice.multiply(profitsItem);
                        if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                            multiply = multiply.multiply(item.getDiscount());
                            proNetSales = proNetSales.multiply(item.getDiscount());
                        }
                        netSales = netSales.add(proNetSales);
                        agentDecimal = agentDecimal.add(multiply);
                    }
                }
            }
            isTEYUE = AgentAccountLog.TEYUE_TRUE;
        } else if (Agent.TYPE_ER.equals(agent.getType())) {
            for (OrderItem item : items) {
                if (item.getIsGifts().intValue() != 1) {
                    Integer productId = item.getProductId();
                    Products product = (Products) Products.dao.findById(productId);
                    BigDecimal erjiPrice = product.getErjiPrice();
                    if (erjiPrice == null) {
                        erjiPrice = new BigDecimal(0.0D);
                    }
                    if (product != null) {
                        BigDecimal profitsItem = new BigDecimal(1).subtract(erjiPrice.multiply(new BigDecimal(0.01D)));
                        BigDecimal proNetSales = erjiPrice.multiply(new BigDecimal(0.01D));
                        BigDecimal itemPrice = item.getPrice().subtract(divide);
                        if ((activityPrice != null) &&
                                (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                                (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                            itemPrice = itemPrice.subtract(activityPrice);
                        }
                        BigDecimal multiply = itemPrice.multiply(profitsItem);
                        if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                            multiply = multiply.multiply(item.getDiscount());
                            proNetSales = proNetSales.multiply(item.getDiscount());
                        }
                        netSales = netSales.add(proNetSales);
                        agentDecimal = agentDecimal.add(multiply);
                    }
                }
            }
        } else if (Agent.TYPE_AREA.equals(agent.getType())) {
            for (OrderItem item : items) {
                if (item.getIsGifts().intValue() != 1) {
                    Integer productId = item.getProductId();
                    Products product = (Products) Products.dao.findById(productId);
                    BigDecimal quyuPrice = product.getQuyuPrice();
                    if (quyuPrice == null) {
                        quyuPrice = new BigDecimal(0.0D);
                    }
                    if (product != null) {
                        BigDecimal profitsItem = new BigDecimal(1).subtract(quyuPrice.multiply(new BigDecimal(0.01D)));
                        BigDecimal proNetSales = quyuPrice.multiply(new BigDecimal(0.01D));
                        BigDecimal itemPrice = item.getPrice().subtract(divide);
                        if ((activityPrice != null) &&
                                (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                                (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                            itemPrice = itemPrice.subtract(activityPrice);
                        }
                        BigDecimal multiply = itemPrice.multiply(profitsItem);
                        if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                            multiply = multiply.multiply(item.getDiscount());
                            proNetSales = proNetSales.multiply(item.getDiscount());
                        }
                        netSales = netSales.add(proNetSales);
                        agentDecimal = agentDecimal.add(multiply);
                    }
                }
            }
        } else {
            return null;
        }
        System.out.println(agentDecimal);
        if ((sonAgentPrice != null) && (sonAgentPrice.compareTo(new BigDecimal(0.0D)) > 0)) {
            profits = agentDecimal.subtract(sonAgentPrice);
            if (profits.compareTo(new BigDecimal(0.0D)) <= 0) {
                profits = new BigDecimal(0.0D);
            }
        } else {
            profits = agentDecimal;
            if (profits.compareTo(new BigDecimal(0.0D)) <= 0) {
                profits = new BigDecimal(0.0D);
            }
        }
        BigDecimal agentAccumulatedIncome = agent.getAccumulatedIncome();
        agent.setAccumulatedIncome(agentAccumulatedIncome.add(order.getTotalAmount()));
        BigDecimal agentPrice = agent.getPrice();
        if (agentPrice == null) {
            agentPrice = new BigDecimal(0.0D);
        }
        BigDecimal allSale = agent.getAllSale();
        if (allSale == null) {
            allSale = new BigDecimal(0);
        }
        if (sonAgentId != null) {
            BigDecimal sonPrice = agent.getSonPrice();
            if (sonPrice == null) {
                sonPrice = new BigDecimal(0.0D);
            }
            agent.setSonPrice(sonPrice.add(sonAgentPrice));
        }
        BigDecimal netSalesAll = agent.getNetSalesAll();
        if (netSalesAll == null) {
            netSalesAll = new BigDecimal(0.0D);
        }
        agent.setAllSale(allSale.add(agentDecimal));
        agent.setPrice(agentPrice.add(profits));
        boolean update = false;
        if (profits.compareTo(new BigDecimal(0.0D)) > 0) {
            update = agent.update();
        }
        if (update) {
            AgentAccountLog agentAccountLog = new AgentAccountLog();
            agentAccountLog.setId(IdGenerateUtils.getId());
            agentAccountLog.setState(AgentAccountLog.STATEIN);
            agentAccountLog.setType(AgentAccountLog.TYPE_ORDERIN);
            agentAccountLog.setBusiId(AgentAccountLog.ACCOUNTTYPEYE);
            agentAccountLog.setPrice(profits);
            agentAccountLog.setOrderPrice(order.getTotalAmount());
            agentAccountLog.setCreateTime(new Date());
            agentAccountLog.setAgentId(agent.getId());
            agentAccountLog.setOrderId(order.getId());
            agentAccountLog.setStatus(Agent.STATUS_SUCCESS);
            agentAccountLog.setIsSonOrder(isSon);
            if (AgentAccountLog.TEYUE_TRUE.equals(isSon)) {
                agentAccountLog.setSonAgentId(sonAgentId);
                agentAccountLog.setSonPrice(sonAgentPrice);
            }
            agentAccountLog.save();
        }
        orderProfits = orderProfits.add(profits);
        ApiResponse apiResponse = new ApiResponse(update, update ? "��������!" : "��������!", orderProfits);
        if (agent.getParentId() != null) {
            Agent parentAgent = (Agent) Agent.dao.findById(agent.getParentId());

            apiResponse = diguiAgent(parentAgent, items, agent.getId(), agentDecimal, order, isTEYUE, new BigDecimal(0.0D), profits);
            return apiResponse;
        }
        return apiResponse;
    }


    private ApiResponse areaAgentAddPrice(Order o, BigDecimal quyuPices) {
        BigDecimal otherProfits = quyuPices;
        if (o == null) {
            return null;
        }
        BigDecimal couponAmount = o.getCouponAmount();
        if (couponAmount == null) {
            couponAmount = new BigDecimal(0.0D);
        }
        List<OrderItem> sumProductItems = OrderItem.dao.findOrderItemByOrderId(o.getId());
        Integer sumProduct = Integer.valueOf(0);
        for (OrderItem item : sumProductItems) {
            if (item.getIsGifts().intValue() == 0) {
                sumProduct = Integer.valueOf(sumProduct.intValue() + item.getNums().intValue());
            }
        }
        BigDecimal divide = new BigDecimal(0.0D);
        if (sumProduct.intValue() != 0) {
            divide = couponAmount.divide(new BigDecimal(sumProduct.intValue()), 2);
        }
        Integer addressId = o.getAddressId();
        UserAddress userAddress = (UserAddress) UserAddress.dao.findById(addressId);
        if (userAddress == null) {
            return null;
        }
        if (o.getCityId() == null) {
            return null;
        }
        AddrCities cities = AddrCities.dao.findByCityId(o.getCityId().toString());
        if (cities == null) {
            return null;
        }
        AgentCity agentCity = null;
        if ((((cities != null ? 1 : 0) & (cities.getIsArea() != null ? 1 : 0)) != 0) && (cities.getIsArea().intValue() == 1)) {
            agentCity = (AgentCity) AgentCity.dao.findFirst("select * from t_addr_areas where areaid=?", new Object[]{o.getCountyId()});
        } else {
            agentCity = AgentCity.dao.findByCityId(o.getCityId());
        }
        if (agentCity == null) {
            return null;
        }
        Agent agent = (Agent) Agent.dao.findById(agentCity.getAgentId());
        if (agent == null) {
            return null;
        }
        List<OrderItem> items = OrderItem.dao.findOrderItemByOrderId(o.getId());
        BigDecimal activityPrice = new BigDecimal(0.0D);
        Integer activityProductSkuId = null;
        Integer activityProductId = null;

        BigDecimal agentDecimal = new BigDecimal(0.0D);
        for (OrderItem item : items) {
            Integer productId = item.getProductId();
            Products product = (Products) Products.dao.findById(productId);
            BigDecimal quyuPrice = product.getQuyuPrice();
            if (quyuPrice == null) {
                quyuPrice = new BigDecimal(0.0D);
            }
            if (product != null) {
                BigDecimal profitsItem = new BigDecimal(1).subtract(quyuPrice.multiply(new BigDecimal(0.01D)));

                BigDecimal itemPrice = item.getPrice().subtract(divide);
                if ((activityPrice != null) &&
                        (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                        (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                    itemPrice = itemPrice.subtract(activityPrice);
                }
                BigDecimal multiply = itemPrice.multiply(profitsItem);
                if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                    multiply = multiply.multiply(item.getDiscount());
                }
                agentDecimal = agentDecimal.add(multiply);
            }
        }
        BigDecimal profits = agentDecimal.subtract(otherProfits);
        if (profits.compareTo(new BigDecimal(0.0D)) < 0) {
            profits = new BigDecimal(0.0D);
        }
        BigDecimal agentAccumulatedIncome = agent.getAccumulatedIncome();
        agent.setAccumulatedIncome(agentAccumulatedIncome.add(o.getTotalAmount()));
        BigDecimal agentPrice = agent.getPrice();
        if (agentPrice == null) {
            agentPrice = new BigDecimal(0.0D);
        }
        BigDecimal allSale = agent.getAllSale();
        if (allSale == null) {
            allSale = new BigDecimal(0);
        }
        agent.setAllSale(allSale.add(profits));
        agent.setPrice(agentPrice.add(profits));
        agentCity.setAllSales(allSale.add(profits));
        agentCity.setAvailPrice(agentPrice.add(profits));
        boolean update = false;
        if (profits.compareTo(new BigDecimal(0.0D)) > 0) {
            agentCity.update();
            update = agent.update();
        }
        if (update) {
            AgentAccountLog agentAccountLog = new AgentAccountLog();
            agentAccountLog.setId(IdGenerateUtils.getId());
            agentAccountLog.setState(AgentAccountLog.STATEIN);
            agentAccountLog.setType(AgentAccountLog.TYPE_ORDERIN);
            agentAccountLog.setBusiId(AgentAccountLog.ACCOUNTTYPEYE);
            agentAccountLog.setPrice(profits);
            agentAccountLog.setOrderPrice(o.getTotalAmount());
            agentAccountLog.setCreateTime(new Date());
            agentAccountLog.setAgentId(agent.getId());
            agentAccountLog.setOrderId(o.getId());
            agentAccountLog.setStatus(Agent.STATUS_SUCCESS);
            agentAccountLog.setIsSonOrder(Integer.valueOf(0));
            if (agentAccountLog.getPrice().compareTo(new BigDecimal(0.0D)) > 0) {
                agentAccountLog.save();
            }
        }
        return new ApiResponse(update, update ? "��������!" : "��������!", profits);
    }

    /**
     * 给区域代理商添加金额
     */
    public ApiResponse addAreaAgentPrice(Agent otherAgent, String orderId, BigDecimal price, BigDecimal otherDiscount) {

//		BigDecimal otherDiscount = otherAgent.getDiscount();
        BigDecimal otherOrderPrice = price.multiply(otherDiscount);
        //每单的利润
        BigDecimal otherProfits = price.subtract(otherOrderPrice);
        Order order = Order.dao.findById(orderId);
        if (order == null) {
            return null;
        }
        Integer addressId = order.getAddressId();
        UserAddress userAddress = UserAddress.dao.findById(addressId);
        if (userAddress == null) {
            return null;
        }
        AgentCity agentCity = AgentCity.dao.findByCityId(userAddress.getCityId());
        if (agentCity == null) {
            return null;
        }
        Agent agent = Agent.dao.findById(agentCity.getAgentId());
        if (agent == null) {
            return null;
        }
        AgentLevel agentLevel = AgentLevel.dao.findById(agentCity.getLevelId());
        if (agentLevel == null) {
            return null;
        }
        BigDecimal discount = agentLevel.getDiscount();
        BigDecimal orderPrice = price.multiply(discount);
        //每单的利润
        BigDecimal profits = price.subtract(orderPrice).subtract(otherProfits);
        //累计销售额
        BigDecimal agentAccumulatedIncome = agent.getAccumulatedIncome();
        agent.setAccumulatedIncome(agentAccumulatedIncome.add(price));
        BigDecimal agentPrice = agent.getPrice();
        if (agentPrice == null) {
            agentPrice = new BigDecimal(0.00);
        }
        BigDecimal allSale = agent.getAllSale();
        if (allSale == null) {
            allSale = new BigDecimal(0);
        }
        agent.setAllSale(allSale.add(profits));
        agent.setPrice(agentPrice.add(profits));
        agentCity.setAllSales(allSale.add(profits));
        agentCity.setAvailPrice(agentPrice.add(profits));
        boolean update = false;
        if (profits.compareTo(new BigDecimal(0.00)) > 0) {
            agentCity.update();
            update = agent.update();
        }
        if (update) {
            //增加余额流水
            AgentAccountLog agentAccountLog = new AgentAccountLog();
            agentAccountLog.setId(IdGenerateUtils.getId());
            agentAccountLog.setState(AgentAccountLog.STATEIN);
            agentAccountLog.setType(AgentAccountLog.TYPE_ORDERIN);
            agentAccountLog.setBusiId(AgentAccountLog.ACCOUNTTYPEYE);
            agentAccountLog.setPrice(profits);
            agentAccountLog.setOrderPrice(price);
            agentAccountLog.setCreateTime(new Date());
            agentAccountLog.setAgentId(agent.getId());
            agentAccountLog.setOrderId(orderId);
            agentAccountLog.setStatus(Agent.STATUS_SUCCESS);
            agentAccountLog.setIsSonOrder(0);
            if (agentAccountLog.getPrice().compareTo(new BigDecimal(0.00)) > 0) {
                agentAccountLog.save();
            }
        }
        return new ApiResponse(update, update ? "操作成功!" : "操作失败!", profits);
    }

    public ApiResponse other(Agent agent, String orderId, BigDecimal price, BigDecimal discount, Integer isSon, Integer sonAgentId, BigDecimal teyeAgentPrice) {
        BigDecimal orderPrice = price.multiply(discount);
        //每单的利润
        BigDecimal profits = price.subtract(orderPrice);
        //累计销售额
        BigDecimal agentAccumulatedIncome = agent.getAccumulatedIncome();
        agent.setAccumulatedIncome(agentAccumulatedIncome.add(price));
        BigDecimal agentPrice = agent.getPrice();
        if (agentPrice == null) {
            agentPrice = new BigDecimal(0.00);
        }
        BigDecimal allSale = agent.getAllSale();
        if (allSale == null) {
            allSale = new BigDecimal(0);
        }
        if (Agent.TYPE_TEYUE.equals(agent.getType())) {
            Agent parentAgent = Agent.dao.findById(agent.getParentId());
            BigDecimal sonPrice = parentAgent.getSonPrice();
            if (sonPrice == null) {
                sonPrice = new BigDecimal(0.00);
            }
            parentAgent.setSonPrice(sonPrice.add(profits));
            parentAgent.update();
        }
        agent.setAllSale(allSale.add(profits));
        agent.setPrice(agentPrice.add(profits));
        boolean update = false;
        if (profits.compareTo(new BigDecimal(0.00)) > 0) {
            update = agent.update();
        }
        if (update) {
            //增加余额流水
            AgentAccountLog agentAccountLog = new AgentAccountLog();
            agentAccountLog.setId(IdGenerateUtils.getId());
            agentAccountLog.setState(AgentAccountLog.STATEIN);
            agentAccountLog.setType(AgentAccountLog.TYPE_ORDERIN);
            agentAccountLog.setBusiId(AgentAccountLog.ACCOUNTTYPEYE);
            agentAccountLog.setPrice(profits);
            agentAccountLog.setOrderPrice(price);
            agentAccountLog.setCreateTime(new Date());
            agentAccountLog.setAgentId(agent.getId());
            agentAccountLog.setOrderId(orderId);
            agentAccountLog.setStatus(Agent.STATUS_SUCCESS);
            agentAccountLog.setIsSonOrder(isSon);
            if (AgentAccountLog.TEYUE_TRUE.equals(isSon)) {
                agentAccountLog.setSonAgentId(sonAgentId);
                agentAccountLog.setSonPrice(teyeAgentPrice);
            }
            agentAccountLog.save();
        }
        return new ApiResponse(update, update ? "操作成功!" : "操作失败!", profits);
    }

    /**
     * 后台是否同意提现的操作
     *
     * @param agentAccountLogId
     * @param state
     * @param adminUser
     * @param bankName
     * @param bankNum
     * @param bankUserName
     */
    public ApiResponse withdrawalOption(String agentAccountLogId, Boolean state, AdminUser adminUser, String bankName, String bankNum, String bankUserName) {
        if (StringUtil.isBlank(agentAccountLogId)) {
            return new ApiResponse(false, "id不能为null!");
        }
        AgentAccountLog accountLog = AgentAccountLog.dao.findById(agentAccountLogId);
        if (accountLog == null) {
            return new ApiResponse(false, "申请编号有错误请查证后再重试!");
        }
        Agent agent = Agent.dao.findById(accountLog.getAgentId());
        if (agent == null) {
            return new ApiResponse(false, "代理商不存在!");
        }
        if (state == null) {
            return new ApiResponse(false, "状态不能为null!");
        }
        ApiResponse apiResponse = new ApiResponse();
        BigDecimal price = accountLog.getPrice();
        if (price == null) {
            price = new BigDecimal(0.00);
        }
        BigDecimal agentIceprice = agent.getIceprice();
        if (agentIceprice == null) {
            agentIceprice = new BigDecimal(0.00);
        }
        if (state) {
            //同意提现

            if (price.compareTo(agentIceprice) > 0) {
                return new ApiResponse(false, "代理商可提现金额不足,请查证后再操作!");
            }
//			if(StringUtil.isBlank(bankName)||StringUtil.isBlank(bankNum)||StringUtil.isBlank(bankUserName)){
//				return new ApiResponse(false,"银行卡信息不能为空!");
//			}
            agent.setIceprice(agentIceprice.subtract(price));
            agent.setSonPrice(new BigDecimal(0.00));
            boolean update = agent.update();
            boolean update1 = false;
            if (update) {
                accountLog.setBankName(bankName);
                accountLog.setBankNum(bankNum);
                accountLog.setBankUserName(bankUserName);
                accountLog.setAdminId(adminUser.getId());
                accountLog.setOptionTime(new Date());
                update1 = accountLog.update();
                if (update1 && Agent.ISPALTFROMTRUE.equals(agent.getIsPlatformAgent())) {
                    //平台打款
                    WeixinAppConfig weixinAppConfig = WeixinAppConfig.dao.findById(2);
                    WeixinUser user = WeixinUser.dao.findById(agent.getId());
                    BigDecimal decimal = accountLog.getPrice();
                    if (AppGlobal.dev_Mode) {
                        decimal = new BigDecimal(0.01);
                    }
//
                    System.out.println("getAppId:" + weixinAppConfig.getAppId());
                    System.out.println("getWxKey:" + weixinAppConfig.getWxKey());
                    System.out.println("getWxMchid:" + weixinAppConfig.getWxMchid());
                    System.out.println("getKeystoreFilePath:" + weixinAppConfig.getKeystoreFilePath());
                    System.out.println("getOpenid:" + user.getOpenid());
                    System.out.println("getId:" + accountLog.getId());
                    System.out.println("getNickname:" + user.getNickname());
                    System.out.println("decimal:" + decimal);

                    WeixinTransferResult transfer = WeixinTransferUtil.transfer(weixinAppConfig.getAppId(), weixinAppConfig.getWxKey(), weixinAppConfig.getWxMchid(),
                            weixinAppConfig.getKeystoreFilePath(), user.getOpenid(), accountLog.getId(), user.getNickname(), decimal, "用户提现");
                    System.out.println("transfer:" + transfer);
                    log.info("平台打款:" + transfer.getReturn_msg());
                    if (transfer.isState()) {
                        accountLog.setStatus(1);
                        accountLog.setTransactionId(transfer.getPayment_no());
                        accountLog.update();
                    } else {
                        accountLog.setStatus(0);
                        accountLog.update();
                        agent.setIceprice(price);
                        agent.update();
                    }


                }
            }
            apiResponse = new ApiResponse(update1 && update, (update1 && update) ? "操作成功!" : "操作失败!");

        } else {
            BigDecimal agentPrice = agent.getPrice();
            if (agentPrice == null) {
                agentPrice = new BigDecimal(0.00);
            }
            agent.setPrice(agentPrice.add(price));
            agent.setIceprice(agentIceprice.subtract(price));
            if (agent.getIceprice().compareTo(new BigDecimal(0.00)) < 0) {
                return new ApiResponse(false, "超出冻结金额范围,请联系管理员重试!");
            }
            boolean update = agent.update();
            boolean update1 = false;
            //不同意提现
            if (update) {
                accountLog.setStatus(3);
                accountLog.setAdminId(adminUser.getId());
                accountLog.setOptionTime(new Date());
                update1 = accountLog.update();
            }
            apiResponse = new ApiResponse(update1, update1 ? "操作成功!" : "操作失败!");
        }
        return apiResponse;
    }

    public BigDecimal findOrderCashBack(Integer agentCityId, BigDecimal productPrice) {
        AgentCity agentCity = AgentCity.dao.findById(agentCityId);
        if (agentCity != null && agentCity.getLevelId() != null) {
            AgentLevel agentLevel = AgentLevel.dao.findById(agentCity.getLevelId());
            if (agentLevel != null) {
                return productPrice.subtract((productPrice.subtract(agentLevel.getDiscount())));
            }
        }
        return new BigDecimal(0);
    }


    /**
     * 获取代理商的所有订单信息
     *
     * @param agentId 代理商id
     */
    public Page<Order> findOrderListByAgentId(Integer agentId, Integer page, Integer pageSize) {
        Page<Order> orderPage = Order.dao.findAgentOrders(agentId, page, pageSize, null, null, null, null, null);
        List<Order> list = orderPage.getList();
        for (Order order : list) {
            List<OrderItem> item = OrderItem.dao.getOrderItemsByOrderId(order.getId());
            order.put("items", item);
        }
        return orderPage;

    }

    public ApiResponse deleteAgentLevel(String id) {
        AgentLevel byId = AgentLevel.dao.findById(id);
        List<AgentCity> cities = AgentCity.dao.findByLevelId(id);
        if (cities != null && cities.size() > 0) {
            return new ApiResponse(false, "该等级已有区域关联,删除失败!");
        }
        boolean delete = AgentLevel.dao.deleteById(id);

        return new ApiResponse(delete, delete ? "删除成功!" : "删除失败!");
    }

    public Page<AgentAccountLog> findAccountListByAgentId(Integer agentId, int getpage, int getpageSize) {
        Page<AgentAccountLog> accountLogList = AgentAccountLog.dao.findAccountLogList(getpage, getpageSize, agentId.toString(), null, 1);
        return accountLogList;
    }

    /**
     * 保存正常代理商
     *
     * @param agent 代理商
     * @param user  用户
     */
    public ApiResponse saveNormalAgent(Agent agent, WeixinUser user) {
        ApiResponse apiResponse = new ApiResponse(false, "保存失败!");
        if (agent.getId() == null) {
            agent.setUserId(user.getId());
            agent.setStatus(AgentCity.STATUS_NOTAUDIT);
            agent.setModifiedTime(new Date());
            boolean save = agent.save();
            if (save) {
                new SendTemplateMessage().sendSubmitRegister(user.getOpenid());
            }

            apiResponse = new ApiResponse(save, save ? "提交成功!" : "提交失败!");
        }
        return apiResponse;
    }

    /**
     * 审核普通代理商
     *
     * @param agentId
     * @param levelId
     * @param status
     * @param logintUser
     */
    public ApiResponse auditNormAgent(String agentId, Integer levelId, Integer status, AdminUser logintUser) {
        Agent agent = Agent.dao.findById(agentId);

        if (Agent.STATUS_SUCCESS.equals(status)) {
            if (agent == null) {
                return new ApiResponse(false, "代理商不存在!");
            }

            if (status == null) {
                return new ApiResponse(false, "审核状态不能为null!");
            }
            if (logintUser == null) {
                return new ApiResponse(false, "当前用户未登录!");
            }
            qrCode(agent);
            agent.setIsPlatformAgent(Agent.ISPALTFROMTRUE);
            agent.setLevelId(levelId);
            agent.setAgentLevel(levelId);
            agent.setStatus(status);
            boolean update = agent.update();
            if (update) {
                String statusStr = "审核通过";
                String content = "您的经销商申请已经审核通过，点击查看";
                String aduit = MessageUtils.ADUIT_SUCCESS_ID;
                String tims = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());
                sendAuditTemplateMsg(statusStr, agent.getAgentName(), content, logintUser.getName(), tims, weixinUser.getOpenid());
                MessageUtils.sendTemplateSMS(agent.getAgentPhone(), aduit, new String[]{""});
                weixinUser.setIsAgent(1);
                weixinUser.update();
            }
            return new ApiResponse(update, update ? "审核成功!" : "审核失败!");
        } else {
            String statusStr = "未通过审核";
            String content = "对不起，您的经销商申请未通过审核。";
            String aduit = MessageUtils.ADUIT_FAIL_ID;
            String tims = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());
            sendAuditTemplateMsg(statusStr, agent.getAgentName(), content, logintUser.getName(), tims, weixinUser.getOpenid());
            auditNo(agent, weixinUser);
            return new ApiResponse(true, "审核完成");
        }


    }

    /**
     * 审核二级代理商
     *
     * @param agentId
     * @param levelId
     * @param status
     * @param logintUser
     */
    public ApiResponse auditErJiAgent(String agentId, Integer levelId, Integer status, AdminUser logintUser, String discountStr) {
        Agent agent = Agent.dao.findById(agentId);

        if (Agent.STATUS_SUCCESS.equals(status)) {
            if (agent == null) {
                return new ApiResponse(false, "代理商不存在!");
            }
//			if (levelId == null)
            if (status == null) {
                return new ApiResponse(false, "审核状态不能为null!");
            }
            if (logintUser == null) {
                return new ApiResponse(false, "当前用户未登录!");
            }
            if (agent.getParentId() == null) {
                qrCode(agent);
                agentQrCode(agent);
                agent.setLevelId(levelId);
                agent.setAgentLevel(levelId);
            } else {
                BigDecimal discount;
                try {
                    if (StringUtil.isBlank(discountStr)) {
                        return new ApiResponse(false, "折扣不能为空!");
                    }
                    discount = new BigDecimal(discountStr);
                    if (discount.compareTo(new BigDecimal(1.00)) != -1) {
                        return new ApiResponse(false, "折扣不能大于1!");
                    }

                } catch (NumberFormatException e) {
                    return new ApiResponse(false, "折扣格式错误!");
                }
                qrCode(agent);
                agent.setIsPlatformAgent(Agent.ISPALTFROMTRUE);

                agent.setAgentLevel(levelId);
            }
            agent.setStatus(status);
            boolean update = agent.update();
            if (update) {
                String statusStr = "审核通过";
                String content = "您的经销商申请已经审核通过，点击查看";
                String audit = MessageUtils.ADUIT_SUCCESS_ID;

                String tims = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());
                sendAuditTemplateMsg(statusStr, agent.getAgentName(), content, logintUser.getName(), tims, weixinUser.getOpenid());
                MessageUtils.sendTemplateSMS(agent.getAgentPhone(), audit, new String[]{""});
                weixinUser.setIsAgent(1);
                weixinUser.update();
            }
            return new ApiResponse(update, update ? "审核成功!" : "审核失败!");
        } else {
            String statusStr = "未通过审核";
            String content = "对不起，您的经销商申请未通过审核。";
            String audit = MessageUtils.ADUIT_FAIL_ID;
            String tims = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());
            sendAuditTemplateMsg(statusStr, agent.getAgentName(), content, logintUser.getName(), tims, weixinUser.getOpenid());
            MessageUtils.sendTemplateSMS(agent.getAgentPhone(), audit, new String[]{""});
            ApiResponse apiResponse = auditNo(agent, weixinUser);

            return apiResponse;

        }


    }

    /**
     * 生成邀请代理商推广码
     *
     * @param agent
     */
    private void agentQrCode(Agent agent) {
        if (agent.getAgentQrCodeImg() == null) {
            //TODO... 修改链接地址
            String url = "/utils/hhframe/auth_userinfo2?agentid=" + agent.getId();
            WxaQrcodeApiExtends wxaQrcodeApiExtends = new WxaQrcodeApiExtends();
            String qrcodeForQiniu = wxaQrcodeApiExtends.createQrcodeXiaoChengXuForQiniu("", url, 430, false);
            agent.setAgentQrCodeImg(qrcodeForQiniu);
        }
    }

    /**
     * 生成邀请用户推广码
     *
     * @param agent
     */
    private void qrCode(Agent agent) {
        if (agent.getQrCodeImg() == null || agent.getExtensionUrl() == null) {
            String url = "/utils/hhframe/auth_userinfo?agentid=" + agent.getId();
            WxaQrcodeApiExtends wxaQrcodeApiExtends = new WxaQrcodeApiExtends();
            String qrcodeForQiniu = wxaQrcodeApiExtends.createQrcodeXiaoChengXuForQiniu("", url, 430, false);

//			String qrCode = QrCodeKit.getQrCode(qrcodeForQiniu);
//			String upload = QiNiuUtil.upload(qrCode, "agent_QrCode_"+agent.getId() + ".gif");
            agent.setQrCodeImg(qrcodeForQiniu);
            agent.setExtensionUrl(qrcodeForQiniu);
        }
    }

    /**
     * 保存特约代理商
     *
     * @param
     * @param name
     * @param phone
     * @param parentId
     * @param authUserId
     */
    public ApiResponse saveByErjiAgent(String name, String phone, Integer parentId, Integer authUserId, Agent parentAgent) {
        AgentPhone agentPhone = new AgentPhone();
        Agent agent = new Agent();
        agent.setParentId(parentAgent.getId());
        agent.setType(Agent.TYPE_ER);
        agent.setIsTwo(Agent.IS_ERJI_FALSE);
        agent.setStatus(Agent.STATUS_SUCCESS);
        agent.setAgentName(name);
        agent.setAgentPhone(phone);
        boolean save = agent.save();
        return new ApiResponse(save, save ? "提交成功!" : "提交失败!");
    }

    public ApiResponse saveErJiAgent(Agent agent, WeixinUser user) {
        ApiResponse apiResponse = new ApiResponse(false, "保存失败!");
        if (agent.getId() == null) {
            agent.setIsTwo(Agent.IS_ERJI_TRUE);
            agent.setUserId(user.getId());
            agent.setStatus(AgentCity.STATUS_NOTAUDIT);
            agent.setModifiedTime(new Date());
            boolean save = agent.save();
            if (save) {
                new SendTemplateMessage().sendSubmitRegister(user.getOpenid());
            }
            apiResponse = new ApiResponse(save, save ? "提交成功!" : "提交失败!");
        }
        return apiResponse;
    }

    /**
     * 查询该经销商下的所有特约经销商
     *
     * @param agentId 代理商id
     */
    public ApiResponse findAuthorizedDealer(Integer page, Integer pageSize, Integer agentId) {
        Agent agent = Agent.dao.findById(agentId);
        if (agent == null) {
            return new ApiResponse(false, "代理商不存在!");
        }
        if (Agent.TYPE_ER.equals(agent.getType()) || Agent.TYPE_AREA.equals(agent.getType())) {
            Page<Agent> authorizedDealer = Agent.dao.findAuthorizedDealer(page, pageSize, agent.getId());
            return new ApiResponse(true, "success", authorizedDealer);

        } else {
            return new ApiResponse(false, "经销商类型错误!");
        }

    }

    /**
     * 审核特约经销商
     *
     * @param agentId
     * @param status
     * @param discountStr
     * @param authUserId
     * @return
     */
    public ApiResponse auditTeYueAgent(String agentId, Integer status,   AdminUser logintUser) {
        Agent agent = Agent.dao.findById(agentId);
        if (agent == null) {
            return new ApiResponse(false, "代理商不存在!");
        }
        BigDecimal discount = new BigDecimal(0);

        if (status == null) {
            return new ApiResponse(false, "审核状态不能为null!");
        }
        if (logintUser == null) {
            return new ApiResponse(false, "当前用户未登录!");
        }


        qrCode(agent);
        agent.setStatus(status);
        boolean update = agent.update();


        if (update) {

            String statusStr = "";
            String content = "";
            if (Agent.STATUS_SUCCESS.equals(agent.getStatus())) {
                statusStr = "审核通过";
                content = "您的经销商申请已经审核通过，点击查看";
            } else if (Agent.STATUS_FAil.equals(agent.getStatus())) {
                statusStr = "未通过审核";
                content = "对不起，您的经销商申请未通过审核。";
            }
            Agent parentAgent = Agent.dao.findById(agent.getParentId());
            String tims = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());
            weixinUser.setIsAgent(1);
            weixinUser.setExtensionId(agent.getId());
            weixinUser.update();
            ApiResult apiResult = sendAuditTemplateMsg(statusStr, agent.getAgentName(), content, parentAgent.getAgentName(), tims, weixinUser.getOpenid());
            MessageUtils.sendTemplateSMS(agent.getAgentPhone(), MessageUtils.ADUIT_SUCCESS_ID, new String[]{""});
        }
        return new ApiResponse(update, update ? "审核成功!" : "审核失败!");
    }

    /**
     * 代理经销商审核推送模板消息
     *
     * @param auditResult     审核结果
     * @param agentName       商家名称
     * @param content         内容
     * @param parentAgentName 审核商家名称
     * @param auditTime       审核时间
     * @param openId          发送人openId
     * @return
     */
    public ApiResult sendAuditTemplateMsg(String auditResult, String agentName, String content, String parentAgentName, String auditTime, String openId) {
        WxaConfigKit.setWxaConfig(WeixinAppConfig.dao.findById(2).getWxaConfigs());//设置对应的微信小程序
        //根据openid 去查找用户
        WeixinUser user = WeixinUser.dao.getUserByOpentId(openId);
        if (user == null || user.getId() == null) {
            log.error("代理商审核推送消息 openid找数据 未找到！  openid ：" + openId);
            return null;
        }
        Boolean isOk = SubscribeMessageKit.api.subSubscribe(user.getId(), SubscribeMessageKit.Subscribe_Agent_Review_Message);
        if (isOk) {
            WxaSubscribeMessage t = new WxaSubscribeMessage();
            t.add("phrase1", auditResult);//审核结果
            t.add("thing2", agentName);//商家名称
            t.add("thing3", content);//内容
            t.add("name4", parentAgentName);//审核人
            t.add("date5", auditTime);//审核时间
            t.setTemplate_id(SubscribeMessageKit.Subscribe_Agent_Review_Message);
            t.setTouser(openId);
            t.setPage("pages/my/my");//打开的页面
            WxaSubscribeMessageApi api = new WxaSubscribeMessageApi();
            ApiResult send = api.send(t);
            if (!send.isSucceed()) {//推送失败
                log.error("推送参数 t：" + JsonKit.toJson(t));
                log.error(" 代理商审核推送消息失败了！send：" + JsonKit.toJson(send));
            }
            return send;
        } else {
            log.info("代理商审核推送消息，推送失败，当前用户没有订阅消息");
            return null;
        }

    }


    /**
     * 代理经销商推送用户下单模板消息
     *
     * @param orderId    订单编号
     * @param userName   买家名称
     * @param orderPrice 订单金额
     * @param payTime    支付时间
     * @param userPhone  用户电话
     * @param openId     发送人openId
     * @return
     */
    public ApiResult sendSaveTemplateMsg(String orderId, String userName, String orderPrice, String payTime, String userPhone, String openId, BigDecimal price) {

        System.out.println(openId);
        WeixinUser userByOpentId = WeixinUser.dao.getUserByOpentId(/*openId*/"o8HP25XyyYPxdgyPPczCLqzAzY4E");
        String unionid = userByOpentId.getUnionid();
        WeixinUser weixinUser = WeixinUser.dao.findGZHUserByUnionId(unionid);
        if (weixinUser == null || weixinUser.getId() == null) {
            log.error("用户下单推送代理商 openid找数据 未找到！  openid ：" + openId);
            return null;
        }
//		ApiConfigKit.setThreadLocalAppId("wxb5f06f42fcae0701");
        ApiConfigKit.setThreadLocalAppId("wxb5f06f42fcae0701");
        ApiConfigKit apiConfigKit = new ApiConfigKit();
//		String access_token = "";
//		DefaultAccessTokenCache defaultAccessTokenCache = new DefaultAccessTokenCache();
//		defaultAccessTokenCache.set("");
//		ApiConfigKit.setAccessTokenCache(defaultAccessTokenCache);
        ApiResult result = TemplateMsgApi.send(TemplateData.New()
                // 消息接收者
                .setTouser(weixinUser.getOpenid())
                // 模板id
                .setTemplate_id("_sA0s0cAFy_gx0nwtcFnjrJSPfoPhiKwCUBZaNTvdMQ")
                // 模板参数
                .add("first", "您的新订单信息如下：", "#999")
                .add("keyword1", orderId, "#999")
                .add("keyword2", payTime)
                .add("remark", "收货人:" + userName + ",联系方式：" + userPhone + ",本单预计收入:" + (price == null ? new BigDecimal(0.00) : price.setScale(2, BigDecimal.ROUND_HALF_UP)))
                .build());
        System.out.println("推送模板消息给代理商==============" + result);
        return result;
    }


    /**
     * 代理经销商推送用户下单模板消息
     *
     * @param orderId    订单编号
     * @param userName   买家名称
     * @param orderPrice 订单金额
     * @param payTime    支付时间
     * @param userPhone  用户电话
     * @param openId     发送人openId
     * @return
     */
    public ApiResult sendSaveTemplateMsg(String orderId, String userName, String orderPrice, String payTime, String userPhone, String openId) {

        System.out.println(openId);
        WeixinUser userByOpentId = WeixinUser.dao.getUserByOpentId(openId);
        String unionid = userByOpentId.getUnionid();
        WeixinUser weixinUser = WeixinUser.dao.findGZHUserByUnionId(unionid);
        if (weixinUser == null || weixinUser.getId() == null) {
            log.error("用户下单推送代理商 openid找数据 未找到！  openid ：" + openId);
            return null;
        }
        ApiConfigKit.setThreadLocalAppId("wxb5f06f42fcae0701");

        ApiResult result = TemplateMsgApi.send(TemplateData.New()
                // 消息接收者
                .setTouser(weixinUser.getOpenid())
                // 模板id
                .setTemplate_id("_sA0s0cAFy_gx0nwtcFnjrJSPfoPhiKwCUBZaNTvdMQ")
                // 模板参数
                .add("first", "您有新的订单待处理", "#999")
                .add("keyword1", orderId, "#999")
                .add("keyword2", payTime)
                .add("remark", "收货人:" + userName + ",联系方式：" + userPhone)
                .build());
        System.out.println("推送模板消息给代理商==============" + result);
        return result;
    }


    public ApiResponse findInfoByAgentId(String agentId) {
        if (StringUtil.isBlank(agentId)) {
            return new ApiResponse(false, "代理商不能为空!");
        }
        Agent agent = Agent.dao.findById(agentId);
        if (agent == null) {
            return new ApiResponse(false, "代理商不能为空!");
        }
        if (Agent.TYPE_ER.equals(agent.getType())) {
            SQLUtils monthSql = new SQLUtils();
            monthSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id in ( ");
            monthSql.append(" select ag.id from t_agent ag where ag.parent_id=66) AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%M')=Month(CurDate())");
            SQLUtils monthOrderSql = new SQLUtils();
            monthOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where log.agent_id in ( ");
            monthOrderSql.append(" select ag.id from t_agent ag where ag.parent_id=66) AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate())");

            SQLUtils yearSql = new SQLUtils();
            yearSql.append(" select sum(price) as price from t_agent_account_log log where log.agent_id in ( ");
            yearSql.append(" select ag.id from t_agent ag where ag.parent_id=66) AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%m')=Month(CurDate()) ");
            SQLUtils yearOrderSql = new SQLUtils();
            yearOrderSql.append(" select sum(order_price) as price from t_agent_account_log log where log.agent_id in ( ");
            yearOrderSql.append(" select ag.id from t_agent ag where ag.parent_id=66) AND log.`status`=1 and log.state=1 and date_format(log.create_time,'%Y')=Year(CurDate()) ");

            BigDecimal monthPrice = Db.queryBigDecimal(monthSql.toString());
            BigDecimal monthOrderPrice = Db.queryBigDecimal(monthOrderSql.toString());
            BigDecimal yearPrice = Db.queryBigDecimal(yearSql.toString());
            BigDecimal yearOrderPrice = Db.queryBigDecimal(yearOrderSql.toString());

            agent.put("monthPrice", monthPrice);
            agent.put("monthOrderPrice", monthOrderPrice);
            agent.put("yearPrice", yearPrice);
            agent.put("yearOrderPrice", yearOrderPrice);
        }

        WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());
        agent.put("headImg", weixinUser.getHeadimgurl());
        agent.put("nickName", weixinUser.getNickname());

        AgentProductSku productSku = AgentProductSku.dao.findFirst("select * from t_agent_product_sku where agent_id=" + agentId);
        if (null != productSku) {
            Integer saleNum = productSku.getSaleNum();
            Integer stockNum = productSku.getStockNum();
            agent.put("saleNum", saleNum);
            agent.put("stockNum", stockNum);
        }


        return new ApiResponse(true, "OK", agent);
    }

    public ApiResponse payPrice(String agentId, String wxAppId, Integer payType) {
        Agent agent = Agent.dao.findById(agentId);
        if (agent != null && Agent.CASH_DEPOSIT_YIZHIFU == agent.getCashDepositState()) {
            return new ApiResponse(false, "已经支付!");
        }
        if (Agent.STATUS_WEICHULI.equals(agent.getStatus())) {

            AgentAccountLog accountLog = new AgentAccountLog();
            accountLog.setType(AgentAccountLog.TYPE_AUDIT);
            accountLog.setState(AgentAccountLog.STATEOUT);
            accountLog.setStatus(AgentAccountLog.STATUS_INTO);
            accountLog.setId(IdGenerateUtils.getId());
            accountLog.setCreateTime(new Date());
            if (Agent.TYPE_ER.equals(agent.getType())) {
                accountLog.setOrderPrice(new BigDecimal(10000));
                accountLog.setPrice(new BigDecimal(10000));
            } else if (Agent.TYPE_AREA.equals(agent.getType())) {
                accountLog.setOrderPrice(new BigDecimal(5000));
                accountLog.setPrice(new BigDecimal(5000));
            }
            accountLog.setAgentId(agent.getId());
            BigDecimal price = accountLog.getPrice();
            BigDecimal decimal = new BigDecimal(0.00);
            if (AppGlobal.dev_Mode) {
                decimal = new BigDecimal(0.01);
            } else {
                decimal = price;
            }
            WeixinUser weixinUser = WeixinUser.dao.findById(agent.getUserId());


            if (payType != null && 4 == payType) {
                JSONObject pay_json;
                agent.setCashDeposit(accountLog.getPrice());
                agent.setCashDepositState(Agent.CASH_DEPOSIT_WEIZHIFU);
                boolean save = accountLog.save();
                if (save) {
                    agent.update();
                    Map<String, Object> signData = new HashMap<String, Object>();
                    signData.put("order_id", accountLog.getId());
                    signData.put("notify_url", AppGlobal.Host_Domain_Name + "/xapp/agent/notify/parseJson");
                    signData.put("total_fee", decimal.doubleValue());
                    pay_json = JSONObject.parseObject(JsonKit.toJson(signData));
                    return new ApiResponse(true, "success", pay_json);
                } else {
                    return new ApiResponse(false, "调用支付失败!");
                }
            } else {


                //调用微信支付//这里是支付
                JSONObject pay_json = JSONObject.parseObject(KusyApi.mini_wxpay(KusyUtil.Api_key,
                        KusyUtil.Sign_Key,
                        wxAppId,
                        weixinUser.getOpenid(),
                        accountLog.getId(),
                        decimal.doubleValue(),
                        "中科易购代理商付款",
                        AppGlobal.Host_Domain_Name + "/xapp/agent/notify"));
                agent.setCashDeposit(accountLog.getPrice());
                agent.setCashDepositState(Agent.CASH_DEPOSIT_WEIZHIFU);
                boolean save = accountLog.save();
                System.err.println();
                if (save) {
                    agent.update();
                }
                return new ApiResponse(true, "success", pay_json);
            }
        } else {
            return new ApiResponse(false, "代理商已经审核通过!");
        }
    }


    /**
     * 代理商自动提现
     *
     * @param authUser
     * @param price
     */
    public ApiResponse AutoWithdrawal(WeixinUser authUser, String price) {
        //平台发展的经销商（区域、二级、三级）个人账户金额点击提现后直接提现至微信钱包，
        Agent agent = Agent.dao.findInfoByUserId(authUser.getId());
        Integer isPlatformAgent = agent.getIsPlatformAgent();
        if (isPlatformAgent != null && isPlatformAgent == 1) {
            if (StringUtil.isBlank(price)) {
                return new ApiResponse(false, "提现金额不能为null!");
            }
            BigDecimal withdrawalPrice = new BigDecimal(0.00);
            try {
                withdrawalPrice = new BigDecimal(price);
            } catch (NumberFormatException e) {
                return new ApiResponse(false, "金额输出错误");
            }
            if (withdrawalPrice.compareTo(new BigDecimal(0.00)) != 1) {
                return new ApiResponse(false, "提现金额必须大于0元");
            }
            BigDecimal agentPrice = agent.getPrice();
            if (agentPrice == null) {
                agentPrice = new BigDecimal(0.00);
            }
            if (withdrawalPrice.compareTo(agentPrice) > 0) {
                return new ApiResponse(false, "提现金额大于剩余金额,提现失败!");
            }
//		if(StringUtil.isBlank(bankName)||StringUtil.isBlank(bankUserName)||StringUtil.isBlank(bankNum)){
//			return new ApiResponse(false,"银行卡信息必填!");
//		}

            BigDecimal iceprice = agent.getIceprice();
            if (iceprice == null) {
                iceprice = new BigDecimal(0.00);
            }
            agent.setIceprice(iceprice.add(withdrawalPrice));
            agent.setPrice(agentPrice.subtract(withdrawalPrice));
            agent.update();
            AgentAccountLog agentAccountLog = new AgentAccountLog();
            agentAccountLog.setId(IdGenerateUtils.getId());
            agentAccountLog.setPrice(withdrawalPrice);
            agentAccountLog.setStatus(AgentAccountLog.STATUS_INTO);
            agentAccountLog.setAccountType(AgentAccountLog.ACCOUNTTYPEYE);
            agentAccountLog.setAgentId(agent.getId());
            agentAccountLog.setState(AgentAccountLog.STATEOUT);
            agentAccountLog.setType(AgentAccountLog.TYPE_WITHDRAWAL);
            agentAccountLog.setCreateTime(new Date());
            boolean save = agentAccountLog.save();
            //平台打款
            if (save) {
                WeixinAppConfig weixinAppConfig = WeixinAppConfig.dao.findById(2);
                WeixinUser user = WeixinUser.dao.findById(agent.getUserId());
                BigDecimal decimal = agentAccountLog.getPrice();
//				if(AppGlobal.dev_Mode){
//					decimal = new BigDecimal(0.01);
//				}
                System.out.println("appID:" + weixinAppConfig.getAppId());
                System.out.println("WxKey:" + weixinAppConfig.getWxKey());
                System.out.println("WxMchid:" + weixinAppConfig.getWxMchid());
                System.out.println("KeystoreFilePath:" + weixinAppConfig.getKeystoreFilePath());

                WeixinTransferResult transfer = WeixinTransferUtil.transfer(weixinAppConfig.getAppId()
                        , weixinAppConfig.getWxKey()
                        , weixinAppConfig.getWxMchid()
                        , weixinAppConfig.getKeystoreFilePath()
                        , user.getOpenid()
                        , agentAccountLog.getId()
                        , user.getNickname()
                        , decimal, "用户提现");
                log.info("平台打款:" + transfer.getReturn_msg());
                if (transfer.isState()) {
                    agent.setIceprice((agent.getIceprice() == null ? new BigDecimal(0.00) : agent.getIceprice()).subtract(withdrawalPrice));
                    boolean update = agent.update();
                    if (update) {
                        agentAccountLog.setStatus(AgentAccountLog.STATUS_SUCCESS);
                        agentAccountLog.setTransactionId(transfer.getPartner_trade_no());
                        agentAccountLog.update();
                    }
                    return new ApiResponse(true, "平台打款成功!");
                } else {
                    agent.setIceprice((agent.getIceprice() == null ? new BigDecimal(0.00) : agent.getIceprice()).subtract(withdrawalPrice));
                    agent.setPrice((agent.getPrice() == null ? new BigDecimal(0.00) : agent.getPrice()).add(withdrawalPrice));
                    boolean update = agent.update();
                    if (update) {
                        agentAccountLog.setStatus(3);
                        agentAccountLog.update();
                    }
                    return new ApiResponse(false, "平台打款失败!");
                }
            }
            return new ApiResponse(false, "操作失败!");
        } else {
            if (StringUtil.isBlank(price)) {
                return new ApiResponse(false, "提现金额不能为null!");
            }
            BigDecimal withdrawalPrice = new BigDecimal(0.00);
            try {
                withdrawalPrice = new BigDecimal(price);
            } catch (NumberFormatException e) {
                return new ApiResponse(false, "金额输出错误");
            }
            if (withdrawalPrice.compareTo(new BigDecimal(0.00)) != 1) {
                return new ApiResponse(false, "提现金额必须大于0元");
            }
            BigDecimal agentPrice = agent.getPrice();
            if (agentPrice == null) {
                agentPrice = new BigDecimal(0.00);
            }
            if (withdrawalPrice.compareTo(agentPrice) > 0) {
                return new ApiResponse(false, "提现金额大于剩余金额,提现失败!");
            }
            BigDecimal iceprice = agent.getIceprice();
            if (iceprice == null) {
                iceprice = new BigDecimal(0.00);
            }
            agent.setIceprice(iceprice.add(withdrawalPrice));
            agent.setPrice(agentPrice.subtract(withdrawalPrice));
            agent.update();
            AgentAccountLog agentAccountLog = new AgentAccountLog();
            agentAccountLog.setId(IdGenerateUtils.getId());
            agentAccountLog.setPrice(withdrawalPrice);
            agentAccountLog.setStatus(2);
            agentAccountLog.setAccountType(AgentAccountLog.ACCOUNTTYPEYE);
            agentAccountLog.setAgentId(agent.getId());
            agentAccountLog.setState(AgentAccountLog.STATEOUT);
            agentAccountLog.setType(AgentAccountLog.TYPE_WITHDRAWAL);
            agentAccountLog.setCreateTime(new Date());
            boolean save = agentAccountLog.save();
            return new ApiResponse(save, save ? "提现申请成功!" : "提现申请失败!");
        }


    }

    public Map<String, BigDecimal> calcDiGui(Agent agent, List<OrderItem> items, Integer sonAgentId, BigDecimal sonAgentPrice, Order order, Integer isSon, BigDecimal sonNetSales, BigDecimal orderProfits) {
        if (agent.getStatus().intValue() == 99) {
            return null;
        }
        BigDecimal activityPrice = new BigDecimal(0.0D);
        Integer activityProductSkuId = null;
        Integer activityProductId = null;
        if (order.getActivityId() != null) {
            UserActivity userActivity = (UserActivity) UserActivity.dao.findById(order.getActivityId());
            Activity activity = (Activity) Activity.dao.findById(userActivity.getActivityId());
            activityProductSkuId = activity.getProductSkuId();
            activityProductId = activity.getProductId();
            activityPrice = activity.getPrice();
        }
        BigDecimal agentDecimal = new BigDecimal(0.0D);
        BigDecimal profits = new BigDecimal(0.0D);
        Integer isTEYUE = AgentAccountLog.TEYUE_FALSE;
        BigDecimal netSales = new BigDecimal(0.0D);

        BigDecimal couponAmount = order.getCouponAmount();
        if (couponAmount == null) {
            couponAmount = new BigDecimal(0.0D);
        }
        List<OrderItem> sumProductItems = OrderItem.dao.findOrderItemByOrderId(order.getId());
        Integer sumProduct = Integer.valueOf(0);
        for (Iterator localIterator = sumProductItems.iterator(); localIterator.hasNext(); ) {
            OrderItem item = (OrderItem) localIterator.next();
            if (item.getIsGifts().intValue() == 0) {
                sumProduct = Integer.valueOf(sumProduct.intValue() + item.getNums().intValue());
            }
        }
        BigDecimal divide = new BigDecimal(0.0D);
        if (sumProduct.intValue() != 0) {
            divide = couponAmount.divide(new BigDecimal(sumProduct.intValue()), 2);
        }
        if (Agent.TYPE_NORM.equals(agent.getType())) {
            for (OrderItem item : items) {
                if (item.getIsGifts().intValue() != 1) {
                    Integer productId = item.getProductId();
                    Products product = (Products) Products.dao.findById(productId);
                    if (product != null) {
                        BigDecimal normPrice = product.getNormPrice();
                        if (normPrice == null) {
                            normPrice = new BigDecimal(0.0D);
                        }
                        BigDecimal profitsItem = new BigDecimal(1).subtract(product.getNormPrice().multiply(new BigDecimal(0.01D)));
                        BigDecimal proNetSales = product.getNormPrice().multiply(new BigDecimal(0.01D));
                        BigDecimal itemPrice = item.getPrice().subtract(divide);
                        if ((activityPrice != null) &&
                                (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                                (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                            itemPrice = itemPrice.subtract(activityPrice);
                        }
                        BigDecimal multiply = itemPrice.multiply(profitsItem);
                        if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                            multiply = multiply.multiply(item.getDiscount());
                            proNetSales = proNetSales.multiply(item.getDiscount());
                        }
                        netSales = netSales.add(proNetSales);
                        agentDecimal = agentDecimal.add(multiply);
                    }
                }
            }
        } else if (Agent.TYPE_TEYUE.equals(agent.getType())) {
            for (OrderItem item : items) {
                if (item.getIsGifts().intValue() != 1) {
                    Integer productId = item.getProductId();
                    Products product = (Products) Products.dao.findById(productId);
                    BigDecimal teyuePrice = product.getTeyuePrice();
                    if (teyuePrice == null) {
                        teyuePrice = new BigDecimal(0.0D);
                    }
                    if (product != null) {
                        BigDecimal profitsItem = new BigDecimal(1).subtract(teyuePrice.multiply(new BigDecimal(0.01D)));
                        BigDecimal proNetSales = teyuePrice.multiply(new BigDecimal(0.01D));
                        BigDecimal itemPrice = item.getPrice().subtract(divide);
                        if ((activityPrice != null) &&
                                (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                                (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                            itemPrice = itemPrice.subtract(activityPrice);
                        }
                        BigDecimal multiply = itemPrice.multiply(profitsItem);
                        if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                            multiply = multiply.multiply(item.getDiscount());
                            proNetSales = proNetSales.multiply(item.getDiscount());
                        }
                        netSales = netSales.add(proNetSales);
                        agentDecimal = agentDecimal.add(multiply);
                    }
                }
            }
            isTEYUE = AgentAccountLog.TEYUE_TRUE;
        } else if (Agent.TYPE_ER.equals(agent.getType())) {
            for (OrderItem item : items) {
                if (item.getIsGifts().intValue() != 1) {
                    Integer productId = item.getProductId();
                    Products product = (Products) Products.dao.findById(productId);
                    BigDecimal erjiPrice = product.getErjiPrice();
                    if (erjiPrice == null) {
                        erjiPrice = new BigDecimal(0.0D);
                    }
                    if (product != null) {
                        BigDecimal profitsItem = new BigDecimal(1).subtract(erjiPrice.multiply(new BigDecimal(0.01D)));
                        BigDecimal proNetSales = erjiPrice.multiply(new BigDecimal(0.01D));
                        BigDecimal itemPrice = item.getPrice().subtract(divide);
                        if ((activityPrice != null) &&
                                (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                                (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                            itemPrice = itemPrice.subtract(activityPrice);
                        }
                        BigDecimal multiply = itemPrice.multiply(profitsItem);
                        if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                            multiply = multiply.multiply(item.getDiscount());
                            proNetSales = proNetSales.multiply(item.getDiscount());
                        }
                        netSales = netSales.add(proNetSales);
                        agentDecimal = agentDecimal.add(multiply);
                    }
                }
            }
        } else if (Agent.TYPE_AREA.equals(agent.getType())) {
            for (OrderItem item : items) {
                if (item.getIsGifts().intValue() != 1) {
                    Integer productId = item.getProductId();
                    Products product = (Products) Products.dao.findById(productId);
                    BigDecimal quyuPrice = product.getQuyuPrice();
                    if (quyuPrice == null) {
                        quyuPrice = new BigDecimal(0.0D);
                    }
                    if (product != null) {
                        BigDecimal profitsItem = new BigDecimal(1).subtract(quyuPrice.multiply(new BigDecimal(0.01D)));
                        BigDecimal proNetSales = quyuPrice.multiply(new BigDecimal(0.01D));
                        BigDecimal itemPrice = item.getPrice().subtract(divide);
                        if ((activityPrice != null) &&
                                (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                                (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                            itemPrice = itemPrice.subtract(activityPrice);
                        }
                        BigDecimal multiply = itemPrice.multiply(profitsItem);
                        if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                            multiply = multiply.multiply(item.getDiscount());
                            proNetSales = proNetSales.multiply(item.getDiscount());
                        }
                        netSales = netSales.add(proNetSales);
                        agentDecimal = agentDecimal.add(multiply);
                    }
                }
            }
        } else {
            return null;
        }
        System.out.println(agentDecimal);
        if ((sonAgentPrice != null) && (sonAgentPrice.compareTo(new BigDecimal(0.0D)) > 0)) {
            profits = agentDecimal.subtract(sonAgentPrice);
            if (profits.compareTo(new BigDecimal(0.0D)) <= 0) {
                profits = new BigDecimal(0.0D);
            }
        } else {
            profits = agentDecimal;
            if (profits.compareTo(new BigDecimal(0.0D)) <= 0) {
                profits = new BigDecimal(0.0D);
            }
        }
        BigDecimal agentAccumulatedIncome = agent.getAccumulatedIncome();
        agent.setAccumulatedIncome(agentAccumulatedIncome.add(order.getTotalAmount()));
        BigDecimal agentPrice = agent.getPrice();
        if (agentPrice == null) {
            agentPrice = new BigDecimal(0.0D);
        }
        BigDecimal allSale = agent.getAllSale();
        if (allSale == null) {
            allSale = new BigDecimal(0);
        }
        if (sonAgentId != null) {
            BigDecimal sonPrice = agent.getSonPrice();
            if (sonPrice == null) {
                sonPrice = new BigDecimal(0.0D);
            }
            agent.setSonPrice(sonPrice.add(sonAgentPrice));
        }
        BigDecimal netSalesAll = agent.getNetSalesAll();
        if (netSalesAll == null) {
            netSalesAll = new BigDecimal(0.0D);
        }
        agent.setAllSale(allSale.add(agentDecimal));
        agent.setPrice(agentPrice.add(profits));

        orderProfits = orderProfits.add(profits);
        Map<String, BigDecimal> map = new HashMap();
        map.put("agentDecimal", agentDecimal);
        map.put("profits", profits);
        return map;
    }


    public BigDecimal sendAreaAgentAddPrice(Order o, BigDecimal quyuPices) {
        BigDecimal otherProfits = quyuPices;
        if (o == null) {
            return null;
        }
        BigDecimal couponAmount = o.getCouponAmount();
        if (couponAmount == null) {
            couponAmount = new BigDecimal(0.0D);
        }
        List<OrderItem> sumProductItems = OrderItem.dao.findOrderItemByOrderId(o.getId());
        Integer sumProduct = Integer.valueOf(0);
        for (OrderItem item : sumProductItems) {
            if (item.getIsGifts().intValue() == 0) {
                sumProduct = Integer.valueOf(sumProduct.intValue() + item.getNums().intValue());
            }
        }
        BigDecimal divide = new BigDecimal(0.0D);
        if (sumProduct.intValue() != 0) {
            divide = couponAmount.divide(new BigDecimal(sumProduct.intValue()), 2);
        }
        Integer addressId = o.getAddressId();
        UserAddress userAddress = (UserAddress) UserAddress.dao.findById(addressId);
        if (userAddress == null) {
            return null;
        }
        if (o.getCityId() == null) {
            return null;
        }
        AddrCities cities = AddrCities.dao.findByCityId(o.getCityId().toString());
        if (cities == null) {
            return null;
        }
        AgentCity agentCity = null;
        if ((((cities != null ? 1 : 0) & (cities.getIsArea() != null ? 1 : 0)) != 0) && (cities.getIsArea().intValue() == 1)) {
            agentCity = (AgentCity) AgentCity.dao.findFirst("select * from t_addr_areas where areaid=?", new Object[]{o.getCountyId()});
        } else {
            agentCity = AgentCity.dao.findByCityId(o.getCityId());
        }
        if (agentCity == null) {
            return null;
        }
        Agent agent = (Agent) Agent.dao.findById(agentCity.getAgentId());
        if (agent == null) {
            return null;
        }
        List<OrderItem> items = OrderItem.dao.findOrderItemByOrderId(o.getId());
        BigDecimal activityPrice = new BigDecimal(0.0D);
        Integer activityProductSkuId = null;
        Integer activityProductId = null;
        Activity activity;
        if (o.getActivityId() != null) {
            UserActivity userActivity = (UserActivity) UserActivity.dao.findById(o.getActivityId());
            activity = (Activity) Activity.dao.findById(userActivity.getActivityId());
            activityProductSkuId = activity.getProductSkuId();
            activityProductId = activity.getProductId();
            activityPrice = activity.getPrice();
        }
        BigDecimal agentDecimal = new BigDecimal(0.0D);
        for (OrderItem item : items) {
            Integer productId = item.getProductId();
            Products product = (Products) Products.dao.findById(productId);
            BigDecimal quyuPrice = product.getQuyuPrice();
            if (quyuPrice == null) {
                quyuPrice = new BigDecimal(0.0D);
            }
            if (product != null) {
                BigDecimal profitsItem = new BigDecimal(1).subtract(quyuPrice.multiply(new BigDecimal(0.01D)));

                BigDecimal itemPrice = item.getPrice().subtract(divide);
                if ((activityPrice != null) &&
                        (product.getId().equals(activityProductId)) && ((activityProductSkuId == null) || (
                        (item.getSkuId() != null) && (item.getSkuId().equals(activityProductSkuId))))) {
                    itemPrice = itemPrice.subtract(activityPrice);
                }
                BigDecimal multiply = itemPrice.multiply(profitsItem);
                if ((item.getDiscount() != null) && (item.getDiscount().compareTo(new BigDecimal(0.0D)) > 0)) {
                    multiply = multiply.multiply(item.getDiscount());
                }
                agentDecimal = agentDecimal.add(multiply);
            }
        }
        BigDecimal profits = agentDecimal.subtract(otherProfits);
        if (profits.compareTo(new BigDecimal(0.0D)) < 0) {
            profits = new BigDecimal(0.0D);
        }
        return profits;
    }


    public Page<AgentCity> findAgentAuditList(int page, int pageSize, String name, String phone, String type) {
        Page<AgentCity> agentList = AgentCity.dao.findAgentAuditList(page, pageSize, name, phone, type);
        return agentList;
    }


}
